使用sed查找和替换字符串会出错

时间:2014-02-26 08:16:48

标签: shell sed

我正在使用shell脚本。我的要求是找到并替换字符串。该字符串也包含“/”char。我收到错误sed:-e expression#1,char 18:unterminated`s'命令。有人可以告诉我应该如何替换具有“/”的字符串?

#!/bin/bash
...
search_string="../conf/TestSystem/Inst1.xml"
rep="Inst1/Instrument.xml"

sed -i 's|${line}|${rep}/g' MasterConfiguration.xml

我尝试使用另一个sed命令但是那个也给出了错误sed:-e expression#1,char 13:`s'的未知选项

sed -e "s/${line}/${rep}/g" MasterConfiguration.xml > tempfile

2 个答案:

答案 0 :(得分:1)

每当你处理shell变量时,你必须将它们从“sed-string”中取出:

例如:

sed -e "s/"${line}"/"${rep}"/g" MasterConfiguration.xml > tempfile

否则sed会按原样处理字符并按字面搜索${line}enter image description here
如你所见,这里没有任何事情发生。

此外,如果您的变量包含/,则需要为sed使用另一个分隔符。在这种情况下,我倾向于使用~,但你可以自由地使用其他字符 - 只是结果并且不要像你的第一个示例-sed-command那样混合它们:

sed 's~'${line}'~'${rep}'/g' //WRONG
sed 's~'${line}'~'${rep}'~g' //RIGHT

结合两者并且它将起作用: enter image description here

答案 1 :(得分:0)

您可以尝试此sed

sed -i "s#${line}#${rep}#g" MasterConfiguration.xml

<强>问题:

相反,你有,

sed -i "s|${line}|${rep}/g" MasterConfiguration.xml

应该是,

sed -i "s|${line}|${rep}|g" MasterConfiguration.xml

<强>语法:

sed "s|pattern|replacement|g"
相关问题