【问题标题】:Replacing a string with different string with SED comand使用 SED 命令将字符串替换为不同的字符串
【发布时间】:2016-11-12 01:48:52
【问题描述】:

我正在尝试使用sed 命令查找和替换特定字符串,但是当我运行该命令时似乎什么也没发生。

查找:

LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined

替换为:

LogFormat "%{X-Forwarded-For}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined

文件内容

hello
LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined
bye

命令

$ sed -i 's/LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined/LogFormat "%{X-Forwarded-For}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined/g' /etc/apache2/apache2.conf

我查看了How do I escape double and single quotes in SED? (bash),但无法确定问题所在。

【问题讨论】:

    标签: sed


    【解决方案1】:

    您的文件在引号前包含反斜杠。您的 sed 正则表达式也是如此,但在 sed 情况下,当您需要文字时,这些是转义字符。您需要转义反斜杠以使其文字化,例如:

    ...\\"%r\\"..
    

    见:

    $ sed 's/LogFormat "%h %l %u %t \\"%r\\" %>s %O \\"%{Referer}i\\" \\"%{User-Agent}i\\"" combined/LogFormat "%{X-Forwarded-For}i %l %u %t \\"%r\\" %>s %b \\"%{Referer}i\\" \\"%{User-Agent}i\\"" combined/g' file
    hello
    LogFormat "%{X-Forwarded-For}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
    bye
    

    但考虑使用捕获组而不是复制替换中的所有文本:

    $ sed 's/\(LogFormat "\)%h\( %l %u %t \\"%r\\" %>s %\)O\( \\"%{Referer}i\\" \\"%{User-Agent}i\\"" combined\)/\1%{X-Forwarded-For}i\2b\3/g' file
    hello
    LogFormat "%{X-Forwarded-For}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
    bye
    

    【讨论】:

      猜你喜欢
      • 2021-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-30
      • 2015-03-24
      • 2014-07-29
      • 2021-10-28
      相关资源
      最近更新 更多