Sed 在 bash 脚本中不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3015645/
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 not working inside bash script
提问by Isabelle
I believe this may be a simple question, but I've looked everywhere and tried some workarounds, but I still haven't solved the problem.
我相信这可能是一个简单的问题,但我到处寻找并尝试了一些解决方法,但我仍然没有解决问题。
Problem description: I have to replace a character inside a file and I can do it easily using the command line:
问题描述:我必须替换文件中的一个字符,我可以使用命令行轻松完成:
sed -e 's/pattern1/pattern2/g' full_path_to_file/file
But when I use the same line inside a bash script I can't seem to be able to replace it, and I don't get an error message, just the file contents without the substitution.
但是当我在 bash 脚本中使用同一行时,我似乎无法替换它,而且我没有收到错误消息,只有没有替换的文件内容。
#!/bin/sh
VAR1="patter1"
VAR2="patter2"
VAR3="full_path_to_file"
sed -e 's/${VAR1}/${VAR2}/g' ${VAR3}
Any help would be appreciated.
任何帮助,将不胜感激。
Thank you very much for your time.
非常感谢您的宝贵时间。
回答by Dmitry Yudakov
Try
尝试
sed -e "s/${VAR1}/${VAR2}/g" ${VAR3}
Bash referencesays:
Bash参考说:
The characters ‘$' and ‘`' retain their special meaning within double quotes
字符 '$' 和 '`' 在双引号内保留其特殊含义
Thus it will be able to resolve your variables
因此它将能够解决您的变量
回答by Carlos Eduardo Baldocchi
I use a script like yours... and mine works as well!
我使用像你这样的脚本……我的也能用!
#!/bin/sh
var1='pattern1'
var2='pattern2'
sed -i "s&$var1&$var2&g" *.html
See that, mine use "-i"... and the seperator character "&" I use is different as yours. The separator character "&" can be used any other character that DOES NOT HAVE AT PATTERN.
看到了,我使用的“-i”...而我使用的分隔符“&”与您的不同。分隔符“&”可用于任何其他在模式中没有的字符。
You can use:
您可以使用:
sed -i "s#$var1#$var2#g" *.html
sed -i "s@$var1@$var2@g" *.html
...
...
If my pattern is: "[email protected]" of course you must use a seperator different like "#", "%"... ok?
如果我的模式是:“[email protected]”,当然你必须使用不同的分隔符,比如“#”、“%”……好吗?