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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 08:26:26  来源:igfitidea点击:

In bash how to replace string variable, and set it into sed command

bashsed

提问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.shinto working_path='$current_path';, but the current_pathhas the /and in the sedcommand, the /is predefined in sedreplace pattern. And I have tried this:

我想运行这个脚本来替换file1.shinto的第一行working_path='$current_path';,但是在命令中current_path/sed/是在sed替换模式中预定义的。我试过这个:

    current_path1="${current_path/\//\\/}"

the above line, I want to replace the /in variable current_pathinto \/, then input the current_path1into the sedcommand, but also has an error.

上面的行,我想更换/在可变current_path\/,然后输入current_path1sed命令,而且还具有一个错误。

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 .shfile? 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//\//\\/}"