如何在SED中使用变量[重复]

时间:2021-08-04 17:06:51

This question already has an answer here:

这个问题在这里已有答案:

I have an xml file with line below

我有一个xml文件,下面有一行

<config-root>/temp</config-root>

Using 'sed' is bash shell script I want to replace the line, the 'sed' script is below

使用'sed'是bash shell脚本我要替换行,'sed'脚本在下面

sed -i 's/<config-root>\(.*\)<\/config-root>/<config-root>\"${dirPath}"<\/config-root>/' Plan.xml

The 'sed' is resulting in

'sed'导致了

<config-root>"${dirPath}"</config-root>

I am expecting the line to be replaced as /opt/shared

我期待将该行替换为/ opt / shared

Can anyone let me know what is wrong in my script? Basically I want to use variable in ‘sed’

任何人都可以让我知道我的脚本有什么问题吗?基本上我想在'sed'中使用变量

Thanks in advance, Babu

在此先感谢,巴布

1 个解决方案

#1


1  

You can use bash to place the variable in the sed script: End the sed script using the single quote ', place the variable in double quotes " and continue the sed program with another single quote ':

您可以使用bash将变量放在sed脚本中:使用单引号'结束sed脚本',将变量放在双引号中“并使用另一个单引号继续sed程序':

sed 's~<config-root>[^<]*</config-root>~<config-root>'"$variable"'</config-root>~' Plan.xml

I would encourage you to use delimiter different from / because the / is part of the pattern (and of the variable) and would need to get escaped otherwise. I used ~ as the delimiter.

我鼓励你使用与/不同的分隔符,因为/是模式(和变量)的一部分,否则需要转义。我用〜作为分隔符。

#1


1  

You can use bash to place the variable in the sed script: End the sed script using the single quote ', place the variable in double quotes " and continue the sed program with another single quote ':

您可以使用bash将变量放在sed脚本中:使用单引号'结束sed脚本',将变量放在双引号中“并使用另一个单引号继续sed程序':

sed 's~<config-root>[^<]*</config-root>~<config-root>'"$variable"'</config-root>~' Plan.xml

I would encourage you to use delimiter different from / because the / is part of the pattern (and of the variable) and would need to get escaped otherwise. I used ~ as the delimiter.

我鼓励你使用与/不同的分隔符,因为/是模式(和变量)的一部分,否则需要转义。我用〜作为分隔符。

相关文章