Swapping IP Addresses In A File With Those From Another File

Hello,
I'm looking for a way to change the IP addresses in a large host file with those of matching hostnames in another file.

For example, I have a file with

file1 contains lines like:

192.168.0.55    hostname hostname.network.lan
192.168.0.52    junkhost junkhost.network.dev
192.168.0.99    newhost-ab

and file2 has:

10.12.1.6          hostname hostname.network.lan
192.168.0.52    junkhost junkhost.network.dev
10.155.1.9        newhost-ab newhost-ab.network.new

In reality, file1 has about 800 lines, and file2 has about 100 lines, and I need to change the IP address in file1 with those new ones in file2 for the hosts that match.

I'm looking at using just sh or ksh with sed/awk, but can't seem to get the logic straight. It would be easy enuf if it were just changing one entry with sed and redirecting to new a file, but when it comes to changing 100+ entries in a file, not sure how to approach it. This is on Solaris.

Any and all help appreciated.

Thanks.

nawk 'FNR==NR{f2[$2]=$1;next} $2 in f2 {$1=f2[$2]}1' file2 file1 
1 Like

Thanks vgersh99. That got me off and running.