bash sed 用双引号替换变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31707923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sed replace variable in double quotes
提问by Ken J
I've created a bash script that takes a parameter. I want to pass that parameter to sed to replace an existing string with another which is composed of the variable:
我创建了一个带参数的 bash 脚本。我想将该参数传递给 sed 以用另一个由变量组成的字符串替换现有字符串:
variable=
echo $variable
sed -i -e 's/name="master"/name="$variable"/g' test
The problem is that the script is not replacing $variable with the parameter, it's just replacing the string with "$variable":
问题是脚本没有用参数替换 $variable,它只是用 "$variable" 替换字符串:
<host name=""$variable"" xmlns="urn:jboss:domain:3:0:>
How can I replace a string in quotes with the variable?
如何用变量替换引号中的字符串?
回答by Sven Marnach
Variable expansion does not happen within single quotes. Do it in double quotes:
单引号内不会发生变量扩展。用双引号做:
sed -i -e 's/name="master"/name="'"$variable"'"/g' test
回答by Avinash Raj
Change your code like his,
像他一样改变你的代码,
sed -i -e 's/name="master"/name="'"$variable"'"/g' test
回答by farrell47
just do like this:
只是这样做:
var=apple
sed -i "s/pineapple/$"