特殊字符的 sed 替换

我该如何用 sed 替换下面的内容?我需要将这个替换成:

set $protection 'disabled';

请注意,我不能将 enabled 改成 disabled,因为它不仅在输入文件的这个位置使用。

我尝试了下面的命令,但是它没有改变任何东西,也没有给我任何错误提示:

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

你可以使用下面的 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';$

INPUT:

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

OUTPUT:

$ echo "set \$protection 'enabled';" | sed "s/set [$]protection 'enabled';/set \$protection 'disabled';/g"
set $protection 'disabled';
2018-06-05 02:25:04
用户967492
用户967492

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

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

将该行更改为所需的值。

2018-06-05 05:36:44