【问题标题】:Getting bad flag in substitute command '/' for sed replacement在替换命令“/”中获取错误标志以进行 sed 替换
【发布时间】:2016-09-28 12:04:16
【问题描述】:

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

我要替换的代码:

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

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

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

我尝试过的:-

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

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

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

【问题讨论】:

    标签: bash sed


    【解决方案1】:

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

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

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

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

    细分:

    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
    

    【讨论】:

    • 我希望它带有双引号,例如 DOMAIN_LOCAL = "http://127.1.1.2:3000";
    • 基本上,每当我使用'/' 作为分隔符时,它会在找到正斜杠后立即停止替换。对吗?
    • @DisplayName 是的,需要注意的一点是变量 $ip 在调用 sed 命令之前展开。所以 sed 不知道 http:// 中的斜杠是文字斜杠,而 not 是分隔符。
    【解决方案2】:

    您可能需要另一个分隔符来代替"/",例如"%"。它对我有用。

    【讨论】:

    • 这个答案可以通过一个例子来改进;我发现这个例子很有用......所有的“/”都必须被替换......在链接例子中是“?” stackoverflow.com/a/1186199/5283424
    【解决方案3】:

    使用#replace / 来避免这个问题 $ sed 's#find#replace#' file

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-16
      • 1970-01-01
      • 1970-01-01
      • 2013-07-06
      • 2020-09-22
      • 1970-01-01
      • 2020-10-09
      相关资源
      最近更新 更多