Reputation: 19
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.
Upvotes: 0
Views: 93
Reputation: 21955
If you wish to use a shell script, try this
#!/bin/bash
awk -v hostname=$2 'BEGIN{RS="}\n"}!($0~hostname) {if($0!="\n"){printf "%s}\n",$0}}' $1 >tempfile.cfg
mv tempfile.cfg $1
Save the script as, say, remove_host
and run it as
./remove_host hostname.cfg host_to_remove
Upvotes: 0
Reputation: 15461
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 spaceba
: branch to label a
to check if next line contains a }
}
has been found /hostname02x/d
: deletes the pattern space if it matches /hostname02x/
Upvotes: 1
Reputation: 195039
this awk one-liner should work for given example:
awk -v RS="[}]\n" -v ORS="}\n" '!/hostname02x/' hostname.cfg
The idea is, make the {...}
block as a record, and check if the record has hostname02x
, we skip the record.
Upvotes: 4