Remove line matching a pattern if next line doesn’t match another pattern

awksedtext processing

Below is extract output from my check script which I would like to print only hostname and error. If there is no error for host delete the entry of hostname too.
The logic I want to use is delete existing line if next line doesn't match "NOT OK"
May use awk or sed…any utility is good for pattern matching.

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

Expected result:

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

Basically:
1. search for term NSAS_HOST
2. check next line for NOT OK. If it exists print lines until we reach the next NSAS_HOST
3. If NOT OK doesn't exist just delete the NSAS_HOST line

Best Answer

with sed :

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

OUTPUT:

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
Related Question