bash 在bash中如何替换字符串变量,并将其设置为sed命令
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19647982/
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
In bash how to replace string variable, and set it into sed command
提问by mining
in a bash script file, I have set one variable like this:
在 bash 脚本文件中,我设置了一个这样的变量:
current_path=`pwd`
sed -i "1s/.*/working_path='$current_path';/" file1.sh
I want to run this script to replace the first line of file1.sh
into working_path='$current_path';
, but the current_path
has the /
and in the sed
command, the /
is predefined in sed
replace pattern.
And I have tried this:
我想运行这个脚本来替换file1.sh
into的第一行working_path='$current_path';
,但是在命令中current_path
有/
和sed
,/
是在sed
替换模式中预定义的。我试过这个:
current_path1="${current_path/\//\\/}"
the above line, I want to replace the /
in variable current_path
into \/
, then input the current_path1
into the sed
command, but also has an error.
上面的行,我想更换/
在可变current_path
进\/
,然后输入current_path1
到sed
命令,而且还具有一个错误。
Could you give me some advice, please? Thanks.
你能给我一些建议吗?谢谢。
回答by Rafa
Try this.
尝试这个。
sed -i -e "1s@.*@working_path='$current_path';@" file1.sh
Use @
instead of /
in the substitute command.
使用@
,而不是/
在替换命令。
回答by glenn Hymanman
You can use different delimiters for the s///
command:
您可以为s///
命令使用不同的分隔符:
current_path=`pwd`
sed -i "1s|.*|working_path='$current_path';|" file1.sh
But you're not really searching and replacing here,, you want to insert the new line and delete the old line:
但是你并不是真正在这里搜索和替换,你想插入新行并删除旧行:
current_path=`pwd`
sed -i -e "1i\working_path='$current_path)';" -e 1d file1.sh
Are you really changing the first line of a .sh
file? Are you deleting the she-bang line?
您真的要更改.sh
文件的第一行吗?你要删除she-bang线吗?
回答by Jun Kawai
Please add a '/' to the beginning of pattern string. It replaces all matches of pattern with string.
请在模式字符串的开头添加一个“/”。它用字符串替换模式的所有匹配项。
current_path1="${current_path//\//\\/}"