Reputation: 117
Below is the shell script I am using to replace 200 plus strings in nagios.cfg.
I want sed to replace all 200 strings in same file but instead its copying the content 200 times with each having one change.
#set -x
cat partthree | while read LINE
do hostnam=`echo $LINE | awk '{print $1}'`
echo $hostnam
a=`less hosts | grep $hostnam -A5 | grep -i md5sum | awk '{print $2}'`
b=`less partthree | grep $hostnam | awk '{print $2}'`
echo $a
echo $b
sed "s/$a/$b/g" hosts >> sample
# sed "s/$a/$b/g" hosts > sample will change only last occurence
done
Tried using sed -i "s/$a/$b/g" hosts directly
@Expected output:
define host {
address sampleaddress
alias samplealaias
host_name samplealhostname
_md5sum def(with replaced string)
}
Output
define host {
address sampleaddress
alias samplealaias
host_name samplealaias
c8h(origanal string) def(string that is supposed to replace original c8h value)
}
Upvotes: 1
Views: 152
Reputation: 1947
The following script should do the job. It starts with the initial hosts
file and performs the individual replacements one after another. The main difference to the original script is that the replacement results are not appended to the result file, but are applied in-place (sed -i
) on the result file.
# start with 'sample' = 'hosts'
cp hosts sample
# perform replacements one after another in 'sample'
cat partthree | while read LINE ; do
hostnam=`echo $LINE | awk '{print $1}'`
a=`less hosts | grep $hostnam -A5 | grep -i md5sum | awk '{print $2}'`
b=`less partthree | grep $hostnam | awk '{print $2}'`
# modify 'sample' in-place
sed -i "s/$a/$b/g" sample
done
Upvotes: 1