Search code examples
bashnslookup

bash replace ip with hostname using nslookup on a file


i have a tempfile that outputs this information

1.2.3.4 34
1.2.3.5 23
1.2.3.6 22

The first columns are ip adresses, and the second one are simultaneos connections to databases, i need to output the first column not as an ip address but as a hostame, and keep the info of the second column

Desired output

hostname1 34
hostname2 23
hostname3 22

thanks in advance...


Solution

  • Something like this maybe:

    #!/bin/bash
    while read ip n
    do
       # Uncomment following to use /etc/hosts
       # name=$(awk -v ip=$ip '$1 ~ ip{print $2}' /etc/hosts)
       # Uncomment following to use nslookup
       # name=$(nslookup $ip| grep "name ="|sed 's/.*=//')
       # Uncomment following line to use dig (thanks to Charles Duffy)
       # name=$(dig +short -x $ip)
       echo $name $n
    done < file