如何用 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
命令:
命令:
sed "s/set [$]protection 'enabled';/set \$protection 'disabled';/g"
解释:
- 只需使用双引号并在类字符组中添加
$
即可避免您的 shell 将$protection
解释为变量 - 如果您需要修改文件,请将命令更改为:
sed -i.back "s/set [$]protection 'enabled';/set\$protection 'disabled';/g"
它将备份您的文件并就地进行修改。 - 如果您要更改的行上没有其他内容,您还可以将开始
^
和结束$
anchor 添加到您的正则表达式中。^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';
关于regex - 带有特殊字符的 sed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50690868/