bash 在用于 sed 替换的替换命令“/”中获取错误标志

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

Getting bad flag in substitute command '/' for sed replacement

bashsed

提问by DisplayName

I am facing one issue while using replace in my sed command. I've a file named a.txt, I want to replace a single line with some other line but I am getting above mentioned error.

我在 sed 命令中使用 replace 时遇到一个问题。我有一个名为 的文件a.txt,我想用其他行替换一行,但出现上述错误。

Code I want to replace:

我要替换的代码:

DOMAIN_LOCAL = "http://127.0.0.1:3000";

I want it to replace with any other ip lets say something like below:-

我希望它替换为任何其他 ip 让我们说如下:-

DOMAIN_LOCAL = "http://127.1.1.2:3000";

What I've tried:-

我试过的:-

ip=http://127.1.1.2:3000
sed "s/DOMAIN_LOCAL = .*$/DOMAIN_LOCAL = "$ip";/g" a.txt

But it is giving me following error. Can somebody help here.

但它给了我以下错误。有人可以在这里帮忙吗。

sed: 1: "s/DOMAIN_LOCAL = .*$/DO ...": bad flag in substitute command: '/'

回答by andlrc

You will need to use another delimiter. And escape the $or use single quotes:

您将需要使用另一个分隔符。并转义$或使用单引号:

% ip="http://127.1.1.2:3000"
% sed 's~DOMAIN_LOCAL = .*$~DOMAIN_LOCAL = "'"$ip"'";~' a.txt
DOMAIN_LOCAL = http://127.1.1.2:3000;

When you use /as a delimiter in the substitute command it will be terminated at the first slash in http://:

当您/substitute 命令中用作分隔符时,它将在第一个斜杠处终止http://

sed 's/DOMAIN_LOCAL = .*$/DOMAIN_LOCAL = http://127.1.1.2:3000;/'
#                                             ^ here

Breakdown:

分解:

sed 's~DOMAIN_LOCAL = .*$~DOMAIN_LOCAL = "'"$ip"'";~' a.txt
#   │                                    ││└ Use double quotes to avoid word splitting and
#   │                                    ││  globbing on $ip
#   │                                    │└ Exit single quotes
#   │                                    └ Literal double quotes
#   └ Using single quotes to avoid having to escape special characters

回答by Darwin.Lau

You may need another delimiter instead of "/", for example "%".It worked for me.

"/"例如"%",您可能需要另一个分隔符而不是 。它对我有用。