使用Sed处理含特殊字符的文本

4
我该如何使用sed替换它?我需要替换这个:
set $protection 'enabled';

为了

set $protection 'disabled';

请注意,我无法将enabled更改为disabled,因为它不仅在输入文件的此位置使用。
我尝试过这个,但它没有改变任何东西,也没有给我任何错误提示:
sed -i "s/set $protection 'enabled';/set $protection 'disabled';/g" /usr/local/openresty/nginx/conf/nginx.conf

可能是 如何在sed中转义单引号? 的重复。 - Sundeep
1
在重复问题中提出的解决方案之一是使用双引号,但在此 OP 的情况下,存在像 $ 这样会导致问题的字符.. 因此,请使用其他提到的技巧。 - Sundeep
1
这种情况的更简单的替代方法是:sed -i '/^set $protection/s/enabled/disabled/' file - dave_thompson_085
2个回答

1
你可以使用以下的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>,为了保险起见,请自动备份您的文件! - Allan

0
这可能适用于您(GNU sed):
sed '/^set $protection '\''enabled'\'';$/c set $protection '\''disabled'\'';' file

将该行更改为所需的值。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接