如果下一行与另一个模式不匹配,则删除与模式匹配的行

如果下一行与另一个模式不匹配,则删除与模式匹配的行

下面是我的检查脚本的提取输出,我只想打印主机名和错误。如果主机没有错误,也删除主机名条目。
我想使用的逻辑是如果下一行与“NOT OK”不匹配则删除现有行
可以使用awksed...任何实用程序都适合模式匹配。

NSAS_HOST:d01-emsacssb01
NSAS_HOST:d01-emsacssb02
NSAS_HOST:emsacssbcon01
NOT OK main load processes
NOT OK 5.3% AXConfigurator
NOT OK eth0.orig is not UP, but ifcfg-eth0.orig sets ONBOOT=yes
NOT OK eth1.bak is not UP, but ifcfg-eth1.bak sets ONBOOT=yes
NOT OK eth1.orig is not UP, but ifcfg-eth1.orig sets ONBOOT=yes
NSAS_HOST:emsacssb03
NOT OK eth0.orig is not UP, but ifcfg-eth0.orig sets ONBOOT=yes
NOT OK eth1.orig is not UP, but ifcfg-eth1.orig sets ONBOOT=yes
NSAS_HOST:emsacsnb01
NSAS_HOST:emsacsnb02
NSAS_HOST:d02-emsacssb01
NSAS_HOST:d02-emsacssb02
NSAS_HOST:b2bcms01
NSAS_HOST:b2bcms02
NSAS_HOST:d02-b2bpgdb01
NOT OK bond0: device speed not determined
NOT OK bond1: device speed not determined

预期结果:

NSAS_HOST:emsacssbcon01
NOT OK main load processes
NOT OK 5.3% AXConfigurator
NOT OK eth0.orig is not UP, but ifcfg-eth0.orig sets ONBOOT=yes
NOT OK eth1.bak is not UP, but ifcfg-eth1.bak sets ONBOOT=yes
NOT OK eth1.orig is not UP, but ifcfg-eth1.orig sets ONBOOT=yes
NSAS_HOST:emsacssb03
NOT OK eth0.orig is not UP, but ifcfg-eth0.orig sets ONBOOT=yes
NOT OK eth1.orig is not UP, but ifcfg-eth1.orig sets ONBOOT=yes
NSAS_HOST:d02-b2bpgdb01
NOT OK bond0: device speed not determined
NOT OK bond1: device speed not determined

基本上:
1. 搜索术语NSAS_HOST
2. 检查下一行是否有NOT OK。如果存在,则打印行,直到到达下NSAS_HOST
3 行。如果NOT OK不存在,则删除该NSAS_HOST

答案1

您可以用于sed这项工作:

sed '/NSAS_HOST/{$d;N;/\n.*NOT OK/!D;}' infile

N这只是在每条匹配的行上拉入ext 行NSAS_HOST(除非$当它d删除模式空间时在 la t 行上)。如果模式空间中的第二行不匹配NOT OK,则D删除直到换行符(即删除模式空间中的第一行)并重新开始循环。

答案2

与 sed :

sed -ne '/NSAS_HOST/{N;/NOT OK/{p}};/NSAS_HOST/!p' FILE 

输出:

NSAS_HOST:emsacssbcon01
NOT OK main load processes
NOT OK 5.3% AXConfigurator
NOT OK eth0.orig is not UP, but ifcfg-eth0.orig sets ONBOOT=yes
NOT OK eth1.bak is not UP, but ifcfg-eth1.bak sets ONBOOT=yes
NOT OK eth1.orig is not UP, but ifcfg-eth1.orig sets ONBOOT=yes
NSAS_HOST:emsacssb03
NOT OK eth0.orig is not UP, but ifcfg-eth0.orig sets ONBOOT=yes
NOT OK eth1.orig is not UP, but ifcfg-eth1.orig sets ONBOOT=yes
NSAS_HOST:d02-b2bpgdb01
NOT OK bond0: device speed not determined
NOT OK bond1: device speed not determined

答案3

在 GNU grep 中使用非常简单选项--no-group-separator除了-B选项:

grep --no-group-separator -B1 ^"NOT OK" log 

或者,如果您grep没有--no-group-separator,但有-B,则删除--各个组之间的行:

grep -B1 ^"NOT OK" log | grep -v ^--$

相关内容