script to grep a pattern from file compare contents with another file and replace

Hi All,
Need help on this

I have 2 files
one file file1 which has several entries as :

define service{
hostgroup_name    !host1,!host5,!host6,.*
service_description check_nrpe
}
 
define service{
hostgroup_name    !host2,!host4,!host6,.*
service_description check_opt
}

another file file2:

host1
host2
host3
host4
host5
host6

I wanted to compare the entries in the line
"hostgroup_name !host1,!host5,!host6,.*" of file1 for each service definition with the contents of the file2 and replace the entries under the hostgroup_name with the missing contents removing the existing content

i.e.,

i wanted the ouput as

define service{
hostgroup_name    host2,host3,host4
service_description check_nrpe
}
 
define service{
hostgroup_name    host1,host3,host5
service_description check_opt
}

:wall:
Thanks,
namitai

Assuming a single line hostgroup_names and no embedded white space characters in the hostnames.

awk 'NR == FNR {
  h[$0]; next
  }
/hostgroup_name/ {
  split($2, t, /[,!]/)
  split(x, _h); hs = x
  for (T in t) _h[t[T]]
  for (H in h) H in _h || hs = hs ? hs "," H : H
  sub(/[^ ]*$/, hs) 	
  }1' file2 file1  
1 Like

Thanks Indeed It works perfectly fine......

:slight_smile: