[英]In bash how to replace string variable, and set it into sed command
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';
我想运行这个脚本将
file1.sh
的第一行file1.sh
为working_path='$current_path';
, but the current_path
has the /
and in the sed
command, the /
is predefined in sed
replace pattern. ,但是
current_path
具有/
并且在sed
命令中, /
是以sed
替换模式预定义的。 And I have tried this: 我试过这个:
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. 上面这行,我想将
/
in变量current_path
替换为\\/
,然后将current_path1
输入到sed
命令中,但也有错误。
Could you give me some advice, please? 你能给我一些建议吗? Thanks.
谢谢。
Try this. 尝试这个。
sed -i -e "1s@.*@working_path='$current_path';@" file1.sh
Use @
instead of /
in the substitute command. 在替换命令中使用
@
而不是/
。
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? 你真的在改变
.sh
文件的第一行吗? Are you deleting the she-bang line? 你是否删除了she-bang线?
Please add a '/' to the beginning of pattern string. 请在模式字符串的开头添加“/”。 It replaces all matches of pattern with string.
它用string替换所有模式匹配。
current_path1="${current_path//\//\\\/}"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.