regex - 带有特殊字符的 sed

标签 regex linux shell sed escaping

如何用 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/

相关文章:

python - 在 Python 中获取匹配字符串的特定模式后出现的数字

javascript - 除非尾部有斜杠,否则如何匹配某个字符后面的任何内容?

regex - 捕获多行、多组到 Powershell 变量

linux -/sys/device/和 dmidecode 报告的不同 CPU 缓存大小

linux - 在 crontab 文件中重命名文件名

regex - 查找 unicode 字符串的十六进制代码

linux - 防止子进程继承父环境

linux - egrep 正则表达式 bash 脚本中的数字变量

mysql - 如何调用此 shell 脚本将 mysqldump 转换为 SQLite 兼容语法

linux - shell 脚本 : Copy directory passed as variable to another directory also as variable passed by user