替换匹配行后面的文本行

Replace text lines following matching line

提问人:miken32 提问时间:3/16/2016 最后编辑:miken32 更新时间:3/16/2016 访问量:50

问:

我正在处理的文件如下所示:

#
# Bulk mode
#
#define command {
#       command_name    process-service-perfdata-file
#       command_line    /usr/libexec/pnp4nagios/process_perfdata.pl --bulk /var/log/pnp4nagios/service-perfdata
#}

#define command {
#       command_name    process-host-perfdata-file
#       command_line    /usr/libexec/pnp4nagios/process_perfdata.pl --bulk /var/log/pnp4nagios/host-perfdata
#}

#
# Bulk with NPCD mode
#
#define command {
#       command_name    process-service-perfdata-file
#       command_line    /bin/mv /var/log/pnp4nagios/service-perfdata /var/spool/pnp4nagios/service-perfdata.$TIMET$
#}

#define command {
#       command_name    process-host-perfdata-file
#       command_line    /bin/mv /var/log/pnp4nagios/host-perfdata /var/spool/pnp4nagios/host-perfdata.$TIMET$
#}

我想取消注释“使用 NPCD 模式批量”标题后面的所有行。到目前为止,我得到的取消注释所有内容,包括标题

sed -E '/Bulk with NPCD mode/,$ {s/^#(.+)/\1/}' /etc/pnp4nagios/misccommands.cfg

在进行任何替换之前,我怎样才能让它跳过“使用 NPCD 模式进行批量”行?我尝试了该命令,但移动到下一行似乎停止了对剩余行的任何进一步处理:n

sed -E '/Bulk with NPCD mode/,$ {n; s/^#(.+)/\1/}' /etc/pnp4nagios/misccommands.cfg
SED

评论


答:

2赞 hek2mgl 3/16/2016 #1

使用范围是正确的方法,但是,将范围边界包含在范围中,这就是为什么您需要显式跳过包含搜索模式的起始行:sed

sed '/Bulk with NPCD/,${/Bulk with NPCD/!s/^#//}'

顺便说一句,替换行首的哈希值。s/^#//

评论

0赞 miken32 3/16/2016
正如你所看到的,我已经熟悉范围了,但这是跳过我不熟悉的一行的语法。多谢。/Bulk with NPCD/!
0赞 hek2mgl 3/16/2016
哦,是的。我应该更仔细地阅读这个问题。很高兴看到它有效!
0赞 potong 3/16/2016 #2

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

sed '/^#.*mode$/h;//!G;/\n# Bulk with NPCD mode$/{/^#\n\|^# Bulk with NPCD mode\n/!s/^#//};P;d' file

将当前模式存储在保留空间中,并将其附加到每一行。如果当前模式是,则删除注释字符(如果它不是模式注释行或空注释)。Bulk with NPCD mode