My requirement is to delete certain lines from my nagios file, might be you have some different requirement but the agenda remains the same.
Lets take an example.
Below mentioned is a part of my hostname.cfg file.
My requiremnet is to make a shell script to delete lines begining 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 admins
alias FEA Preprod
}
Sed Method
# sed -i.bak '/define host/ {:a;/}/!{N;ba};/hostname02x/d}' hostname.cfg
Awk Method
Lets take an example.
Below mentioned is a part of my hostname.cfg file.
My requiremnet is to make a shell script to delete lines begining 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 admins
alias FEA Preprod
}
Sed Method
# sed -i.bak '/define host/ {:a;/}/!{N;ba};/hostname02x/d}' hostname.cfg
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 labela
to check if next line contains a}
- when loop ends,
}
has been found /hostname02x/d
: deletes the pattern space if it matches/hostname02x/
Awk Method
awk -v RS="[}]\n" -v ORS="}\n" '!/hostname02x/' hostname.cfg
No comments:
Post a Comment