mailman
mailman

Reputation: 305

How to compare 2 files and replace words for matched lines in file2 in bash?

FILE1 (/var/widenet.jcml) holds the LAN's server entries while FILE2 (hosts.out) contains a list of IPs. My idea is to use FILE2 to search for IPs on FILE1 and update the entries based on matched IPs.

This is how FILE1 looks

[romolo@remo11g ~]$ grep -F -f hosts.out /var/widenet.jcml |head -2
2548,0,00:1D:55:00:D4:D1,10.0.209.76,wd18-209-76-man 91.widenet.lan,10.0.101.2,255.255.0.0,NULL,NULL,NULL,NULL,NULL,NULL,NAS,ALL
2549,0,00:1D:55:00:D4:D2,10.0.209.77,wd18-209-77-man 91.widenet.lan,10.0.101.2,255.255.0.0,NULL,NULL,NULL,NULL,NULL,NULL,NAS,ALL

While FILE2 is essentially a list of IPs, one IP per line

cat hosts.out
 10.0.209.76
 10.0.209.77
 10.0.209.158
 10.0.209.105
 10.0.209.161
 10.0.209.169
 10.0.209.228

Basically FILE2 contains 160 IPs which entries in /var/widenet.jcml are needed to be updated. In specific the word NAS on column 14 of /var/widenet.jcml needs to be replaced with SAS.

I came up with the following syntax, however instead of just replacing the word NAS for the matched IPs, it will instead replace every entries in FILE1 which does contain the word NAS, therefore ignoring the list of IPs from FILE2.

grep -F -f hosts.out /var/widenet.jcml |awk -F"," '{print$4,$14}' |xargs -I '{}' sed -i 's/NAS/SAS/g' /var/widenet.jcml

I spent hours googling for an answer but I couldn't find any examples that cover search and replace between two text files. Thanks

Upvotes: 2

Views: 82

Answers (2)

Ed Morton
Ed Morton

Reputation: 203209

Assuming file2 doesn't really have leading blanks (if it does it's an easy tweak to fix):

$ awk 'BEGIN{FS=OFS=","} NR==FNR{ips[$1];next} $4 in ips{$14="SAS"} 1' file2 file1
2548,0,00:1D:55:00:D4:D1,10.0.209.76,wd18-209-76-man 91.widenet.lan,10.0.101.2,255.255.0.0,NULL,NULL,NULL,NULL,NULL,NULL,SAS,ALL
2549,0,00:1D:55:00:D4:D2,10.0.209.77,wd18-209-77-man 91.widenet.lan,10.0.101.2,255.255.0.0,NULL,NULL,NULL,NULL,NULL,NULL,SAS,ALL

Upvotes: 2

Paul Dawson
Paul Dawson

Reputation: 1382

If I understand the question correctly, you only want to change NAS to SAS per IP address found in hosts.out?

while read line
 do 
 grep $line file1 | sed 's/NAS/SAS/g' >> results
 done < hosts.out 

Upvotes: 2

Related Questions