linux - 使用 sed 替换双引号和空格

标签 linux unix

我在 rhel5 上,遇到以下问题: 我有一个函数可以用我想要的文本替换给定行中的所有内容。一切正常,直到我需要放置双引号。以下是代码:

ReplaceLine()
{
       txnFile="File.xml"
        if [ "$2" == "enable" ];then
                replace="<ref bean=\\"$3\\"/>"
        else
                replace="<!--<ref bean=\\"$3\\"/>-->"
        fi
        sed -i "$1s/.*/$replace/" $txnFile 
}

$1=line number
$2=enable/disable
$3=string to be put

当前代码将文件中的给定行替换为:

<ref bean=beginEventBean/>

我想要的是:

<ref bean="beginEventBean"/>

注意缺少的双引号。此外,我在 sed 中使用了双引号,因为没有它们,变量中的空格会导致 sed 抛出错误。

请帮助我了解我在哪里走错了路。已经为此花费了几个小时。

最佳答案

您忘记转义关闭标签的正斜杠。然后你放了两个斜线。

# one line solution
# sed -i "$1s/.*/<ref bean=\"$3\"\/>/" $txnFile
#                          ^   ^ ^

ReplaceLine()
{
     txnFile="File.xml"
     if [ "$2" == "enable" ];then
            replace="<ref bean=\"$3\"\/>"
     else
            replace="<!--<ref bean=\"$3\"\/>-->"
     fi
     sed -i "$1s/.*/$replace/" $txnFile 
}

关于linux - 使用 sed 替换双引号和空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13173513/

相关文章:

python - python写的一个正在运行的服务器进程如何查找绑定(bind)地址和端口?

linux - 仅在 debian 命令行安装中抛光字符

linux - 如何引用先前输出中的特定行?

c - 在 C 可执行文件中动态包含文本

linux - 将当前目录存储在变量中,并使用变量来存储从前一个变量开发的路径

c -\033 unix 中的提示符

linux - FTP Shell 脚本不工作

python - 如何仅过滤 Bash(linux)或 Python 文件中的可打印字符?

bash - ffmpeg 命令在 python 中使用时出错

c - 使用通配符操作输入 .txt