I have a file that contains multiple IP addresses and hostnames, and another file that contains some folders with many IP addresses per line.
ip_hostname.txt
host1 10.1.1.1
host2 10.2.2.2
host3 10.3.3.3
host100 10.50.50.50
path_ips.txt
/path1/foo/bar 10.1.1.1 10.2.2.2 10.3.3.3
/path2/foo/bar 10.3.3.3 10.7.7.7
/path3/foo/bar 10.4.4.4 10.8.8.8 10.29.29.29 10.75.75.75
/path100/foo/bar 10.60.60.60
I want to replace the IP addresses from path_ips.txt file with the hostname from ip_hostname.txt file that matches each IP address.
Desired output for path_ips.txt
/path1/foo/bar host1 host2 host3
/path2/foo/bar host3 host7
/path3/foo/bar host4 host8 host29 host75
/path100/foo/bar host60
I tried to do it with sed in a nested while read loop as follows:
#!/bin/sh
while read -r line
do
IP=$(echo $line| awk '{print $1}')
HN=$(echo $line| awk '{print $2}')
while read -r line2
do
sed -i "s/$IP/$HN/g" path_ips.txt
echo $line2 #to see the progress
done < path_ips.txt
done < ip_hostname.txt
And it worked well the first time when the list of IP addresses and hostnames is not so large, but when I tried to do it using a larger list in ip_hostname.txt file, it behaves strangely and the outcome is not as desired. It is needless to mention that it takes too long for it to finish.
Is there a better and efficient way to do it?