如何在SED中使用变量

时间:2014-03-27 20:31:26

标签: linux bash shell unix sed

我有一个xml文件,其中包含

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

使用&#39; sed&#39;是bash shell脚本我要替换该行, &#39; sed&#39;脚本在下面

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

&#39; sed&#39;导致

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

我希望将该行替换为/ opt / shared

有谁能让我知道我的剧本有什么问题?基本上我想在'sed'中使用变量

提前致谢, 巴布

1 个答案:

答案 0 :(得分:1)

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

'

我建议您使用与sed 's~<config-root>[^<]*</config-root>~<config-root>'"$variable"'</config-root>~' Plan.xml 不同的分隔符,因为/是模式(和变量)的一部分,否则需要进行转义。我使用/作为分隔符。