【问题标题】:Sed with special caracters带有特殊字符的sed
【发布时间】:2018-11-14 09:30:35
【问题描述】:

如何将其替换为 sed ?我需要替换这个:

set $protection 'enabled';

到

set $protection 'disabled';

请注意,我无法将enabled sed 到disabled,因为它不仅用于输入文件中的这个位置。

我试过这个,但它没有改变任何东西,但没有给我任何错误:

sed -i "s/set $protection 'enabled';/set $protection 'disabled';/g" /usr/local/openresty/nginx/conf/nginx.conf

【问题讨论】:

  • 副本中建议的解决方案之一是使用双引号,但在 OP 的情况下,有像 $ 这样的字符会导致问题..所以使用提到的其他技巧..跨度>
  • 这种情况下更简单的替代方案:sed -i '/^set $protection/s/enabled/disabled/' file

标签: regex linux shell sed escaping


【解决方案1】:

这可能对你有用(GNU sed):

sed '/^set $protection '\''enabled'\'';$/c set $protection '\''disabled'\'';' file

将该行更改为所需的值。

【讨论】:

    【解决方案2】:

    您可以使用以下sed 命令:

    CMD:

    sed "s/set [$]protection 'enabled';/set \$protection 'disabled';/g"
    

    解释:

    • 只需使用双引号并在类字符组中添加$,以避免您的shell 将$protection 解释为变量
    • 如果您需要修改文件,请将您的命令更改为:sed -i.back "s/set [$]protection 'enabled';/set \$protection 'disabled';/g",它将备份您的文件并就地进行修改。
    • 如果您想要更改的行中没有其他内容,您还可以将起始 ^ 和关闭 $ 锚添加到您的正则表达式中。 ^set [$]protection 'enabled';$

    输入:

    $ echo "set \$protection 'enabled';"
    set $protection 'enabled';
    

    输出:

    $ echo "set \$protection 'enabled';" | sed "s/set [$]protection 'enabled';/set \$protection 'disabled';/g"
    set $protection 'disabled';
    

    【讨论】:

    • 运行:sed -i.bak "s/set [$]protection 'enabled';/set \$protection 'disabled';/g" <INPUT_FILE>,备份您的文件以防万一,应该自动备份!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-02
    • 2017-05-05
    • 2018-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多