Linux 使用变量时 sed 替换不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5156293/
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 replacement not working when using variables
提问by London
something strange is happening when trying to replace string with sed. This works :
尝试用 sed 替换字符串时发生了一些奇怪的事情。这有效:
find /home/loni/config -type f -exec sed -i 's/some_pattern/replacement/g' {} \;
So it works when I manually type the strings. But in the case below replacement doesn't occur :
所以当我手动输入字符串时它会起作用。但在以下情况下,不会发生替换:
find /home/loni/config -type f -exec sed -i 's/${PATTERN}/${REPLACEMENT}/g' {} \;
When I echo these two variables PATTERN and REPLACEMENT they have the correct values.
当我回显这两个变量 PATTERN 和 REPLACEMENT 时,它们具有正确的值。
I'm trying to replace all occurences of pattern string with replacement string in all files in my config directory.
我试图在我的 config 目录中的所有文件中用替换字符串替换所有出现的模式字符串。
采纳答案by Erich Kitzmueller
Try
尝试
find /home/loni/config -type f -exec sed -i "s/${PATTERN}/${REPLACEMENT}/g" {} \;
instead. The ' quotes don't expand variables.
反而。' 引号不会扩展变量。
回答by Bernhard
Not sure if I got this right, but if you want to replace the ${PATTERN} with ${REPLACEMENT} literally you have to escape the dollar and maybe the braces, those are reserved characters in regular expressions:
不确定我是否正确,但如果你想用 ${REPLACEMENT} 替换 ${PATTERN} 字面上你必须转义美元和大括号,这些是正则表达式中的保留字符:
find /home/loni/config -type f -exec sed -i -e 's/$\{PATTERN\}/$\{REPLACEMENT\}/g' {} \;