如何在 sed 中使用 bash 脚本变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3204302/
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
How to use a bash script variable with sed
提问by Steve McLeod
I execute the following bash script:
我执行以下 bash 脚本:
#!/bin/bash
version=
echo $version
sed 's/${version.number}/$version/' template.txt > readme.txt
I'm expecting to replace all instances of ${version.number} with the contents of the variable "version". Instead the literal text $version is being inserted.
我希望用变量“version”的内容替换 ${version.number} 的所有实例。相反,正在插入文字文本 $version。
What do I need to do to make sed use the current value of $version instead?
我需要做什么才能使 sed 使用 $version 的当前值?
回答by Matthew Flaschen
sed "s/${version.number}/$version/" template.txt > readme.txt
Only double quotes do dollar-sign replacement. That also means single quotes don't require the dollar sign to be escaped.
只有双引号做美元符号替换。这也意味着单引号不需要转义美元符号。
回答by Tobias Kienzler
You could also simply unquote the variables
您也可以简单地取消引用变量
sed 's/'${version.number}'/'$version'/' template.txt > readme.txt
回答by J Mac
It's a bit old, but it might still be helpful... For me it worked using a double escape as Philip said (and escaping parenthesis, if you use them...):
它有点旧,但它可能仍然有帮助......对我来说,它使用菲利普所说的双重转义(和转义括号,如果你使用它们......):
#!/bin/bash
LIVE_DB_NAME='wordpress';
STAGING='staging';
sed -r "s/define\('DB_NAME', '[a-zA-Z0-9]+'\);/define('DB_NAME', '\${LIVE_DB_NAME}');/" ${STAGING}/wp-config.php >tmp1;