正则表达式,用于使用sed替换捕获组内容

时间:2019-05-31 04:50:09

标签: regex bash sed replace

在多个目录中具有inputs.conf文件,这些文件需要匹配并解析每个节,并将index =修改为index = secure。 这是inputs.conf中的文件类型,也可以运行脚本以在此目录(_GWAS_pr_linux_t1 / local / inputs.conf)中找到输入文件以修改索引

    [monitor:///var/log/cron]
    sourcetype=linux_secure
    index=

    [monitor:///var/log/secure]
    sourcetype=linux_secure
    index=

    [monitor:///var/log/messages]
    sourcetype=linux
    index=power

    [monitor:///var/log/spooler]
    sourcetype=syslog
    index = 

    [monitor:///var/log/audit/audit.log]
    sourcetype=syslog
    index=

    [monitor:///var/log//maillog]
    sourcetype=syslog
    index=

    sed -i -e 's/.*(?s)((\[monitor\:\/\/\/var\/log\/messages|secure\]).*?)(?:(?:\r*\n){2})' /index=secure *linux*/local/inputs.conf

############################
match each stanza and modify index name to index=windows
inputs file in this dir (_GWAS_pr_window_t1/local/inputs.conf)


    [WinEventLog://Application]
    checkpointInterval = 5
    current_only = 0
    disabled =0 
    start_from = oldest
    index = 

    [WinEventLog://Security]
    checkpointInterval = 5
    current_only = 0
    disabled =0 
    start_from = oldest
    index = 

    [WinEventLog://System]
    checkpointInterval = 5
    current_only = 0
    disabled =0 
    start_from = oldest
    index = 

    [WinEventLog://ForwardedEvents]
    checkpointInterval = 5
    current_only = 0
    disabled =0 
    start_from = oldest
    index = 

    [WinEventLog://Setup]
    checkpointInterval = 5
    current_only = 0
    disabled =0 
    start_from = oldest
    index = 

    sed -i -e 's/.*(?s)((\[WinEventLog:\/\/Application|Security|System|ForwardedEvents|Setup\]).*?)(?:(?:\r\n){2}) /index=window *window*/local/inputs.conf

2 个答案:

答案 0 :(得分:1)

您可以将perl与-0 mode一起使用,而不是使用sed逐行读取。例如,您可以在第1组中捕获这一部分:

[monitor:///var/log/messages]
sourcetype=linux
index=

其次是匹配power

然后在替换中,您可以引用组1并添加安全的$1secure,以便替换匹配的电源。

(\[monitor:///var/log/(?:messages|secure)\](?:(?:\R.*){2})index=)power

Regex demo

perl -0p -i.bak -e 's#(\[monitor:///var/log/(?:messages|secure)\](?:(?:\R.*){2})index=)power#$1secure#g' inputs.conf

结果:

[monitor:///var/log/messages]
sourcetype=linux
index=secure

更新

如果要匹配注释中列出的任何单词并将其替换为索引之后的单词,则可以使用2个捕获组:

perl -0p -i.bak -e 's#(\[monitor:///var/log/(messages|secure|cron|spooler|audit\.log)\](?:(?:\R.*){2})index=).*#$1$2#g' inputs.conf

模式

(\[monitor:///var/log/(messages|secure|cron|spooler|audit\.log)\](?:(?:\R.*){2})index=).*

Regex demo

结果:

[monitor:///var/log/messages]
  sourcetype=linux
index=messages

[monitor:///var/log/secure]
  sourcetype=linux
index=secure

答案 1 :(得分:0)

这可能对您有用(GNU sed):

sed -E '/^\[/{h;b};G;s/^(index=)power\n.*(messages|secure)\]$/\1secure/;P;d' file

这会将每个节的第一行附加到其他行,并使用模式匹配,将power替换为secure