首页 > 解决方案 > SED - 更改行中的字符串,仅当该行以

问题描述

我尝试了很多事情并进行了一些搜索,但没有找到合适的方法:

我想修改几台服务器上的 Apache LogFormat 定义(很多)。所以:在 httpd.conf 中,替换这个:

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

有了这个:

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

无需修改:

    CustomLog "logs/access_log" common
    CustomLog "logs/access_log" combined

所以:我正在寻找 s\" com\ %T" com\g',但仅限于包含的行LogFormat

我渴望做这样的事情。

标签: sed

解决方案


使用 Ansible 等专用解决方案会更好地为您服务,但使用 sed,您可以执行以下操作:

sed -i '/^LogFormat/s/" combined.*$/ %T&/' httpd.conf

搜索以“LogFormat”开头的所有行,然后用双引号、空格和“combined”替换空格、“%T”和识别的模式。


推荐阅读