Search code examples
bashmappinghostnamehosts

How to create network file based on IP address from file similar to /etc/hosts


I have a file which maps IP address to hostnames. Its format is similar to hosts file and contains a list of IP address to hostname mapping.

eg.

10.200.99.1    master1
10.200.99.2    master2
10.200.99.3    master3
10.200.99.4    slave1
10.200.99.5    slave2
10.200.99.6    slave3
...
...
...

I would like to create network file (/etc/sysconfig/network) for all the IP address mentioned in the file.

The format of network file is where the hostname is mentioned based on hosts file.

NETWORKING=yes
HOSTNAME=master1
NOZEROCONF=yes

For every IP Address the network file is created in a directory named by IP Address i.e. network/{IPAddress}.

For example for master1 the path of file should be network/10.200.99.1 and for master2 the path should be network/10.200.99.2.

How can i do so?

Till now I have obtained IPAdress by following command echo $(<hosts) | awk '{print $1}' and Hostname by echo $(<hosts) | awk '{print $2}. But this only prints the contents of first line of the hosts file.


Solution

  • Reads ip and hostname from hosts and writes desired output to network/$ip.

    while read ip hostname; do
        printf '%s\n' "NETWORKING=yes" "HOSTNAME=$hostname" "NOZEROCONF NF=yes" > network/$ip
    done < hosts