Kunal Saha Kunal Saha - 6 months ago 8
Bash Question

Want to delete few lines above and below certain string

My requirement is to delete certain lines from my

nagios
file

Below mentioned is a part of my
hotname.cfg
file.
My requirement is to make a shell script to delete lines beginning from
"define host {" upto "}"

and the variable input
( read )
to fetch from user is just the host_name which can differ.

here i want to delete all entries relevant to host_name --> hostname02x
so i need to delete entries relevant to it beginning from
"define host {" upto "}"
, so that the file which earlier look

#cat hostname.cfg

define host{
use linux-server ; Name of host template to use
host_name hostname01x
hostgroups COT-Servers
contact_groups admins
alias FEA Preprod
}

define host{
use linux-server ; Name of host template to use
host_name hostname02x
hostgroups COT-Servers
contact_groups admins
alias Grid Engine
}


looks like...

#cat hostname.cfg

define host{
use linux-server ; Name of host template to use
host_name hostname01x
hostgroups COT-Servers
contact_groups gecotadmins
alias FEA Preprod
}


I used several methods to delete such entry but none of my algorithms works perfectly.

Answer

With sed :

sed '/define host/ {:a;/}/!{N;ba};/hostname02x/d}' hotname.cfg

It loops over all blocks from /define host/ upto next } : each line in block is added to the pattern space with N and the pattern space matching hostname02x is deleted.

Explanation :

  • /define host/ : starting from /define host/
  • :a : a label for upcoming loop
  • /}/! : if } is not found...
  • N : append the line to the pattern space
  • ba : branch to label a to check if next line contains a }
  • when loop ends, } has been found
  • /hostname02x/d : deletes the pattern space if it matches /hostname02x/
Comments