bash 使用 sed 用带有斜杠的定义变量替换带有空格的文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15236237/
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-09 23:25:27  来源:igfitidea点击:

Using sed to replace text with spaces with a defined variable with slashs

bashunixsed

提问by NPB

I am trying to use sed to replace a line with spaces with a defined variable.

我正在尝试使用 sed 用定义的变量替换带有空格的行。

For example,

例如,

I want to replace 'a dumb string' with $lan, and lan="~/afile.py

我想用 $lan 和 lan="~/afile.py 替换“一个哑字符串”

I assumed the line would be

我以为这条线是

sed "s/a dumb string/$lan/g" file.txt

but this leave the 'a dumb string' part blank in the file.txt.

但这将 file.txt 中的“哑字符串”部分留空。

My problem seems simple enough. Any help is much appreciated.

我的问题似乎很简单。任何帮助深表感谢。

回答by NPB

I determined that because my @lan variable has slashes in it, I need to use the sed command using :

我确定因为我的@lan 变量中有斜杠,所以我需要使用 sed 命令:

For example

例如

sed "s:a dumb string:$lan:g" file.txt

This is probably a novice mistake, but I'm not that familiar with sed. Thank you for your help.

这可能是一个新手错误,但我对 sed 不太熟悉。感谢您的帮助。

回答by FatalError

sedis not aware that you're passing a variable -- it'll be interpreted as just another part of your regex. If your substitution contains slashes, the easiest thing to do is use an alternate separator char, like this:

sed不知道您正在传递一个变量——它会被解释为正则表达式的另一部分。如果您的替换包含斜杠,最简单的方法是使用备用分隔符字符,如下所示:

sed "s|a dumb string|$lan|g" file.txt

回答by Vidya Patil

Sometime space in search string does not work so needed to use [[:space:]] in centos.

有时搜索字符串中的空格不起作用,因此需要在 centos 中使用 [[:space:]] 。

    sed -i 's/User[[:space:]]daemon/User apache/' httpd1.conf