for loop to retrieve IPs using nslookup

I had to decommission a bunch of servers for which I didn’t have an IP list, needed for the paperwork.

Luckily, we still had the DNS records for those machines and, using a for loop and the almighty awk, I managed to retrieve all the information I needed:

for h in `cat hostname.list`; do nslookup $h | grep ^Name -A1 | awk '{print $2}'; echo; done > ip.list

This one-liner will output the IP and the corresponding hostname in a file.

AWK basics

Printing columns

Print all the columns:

$ awk '{print $0}' FILE

Print the 1 column:

$ awk '{print $1}' FILE

Print the last column:

$ awk '{print $NF}' FILE

Print multiple columns:

$ awk '{print $1 $3}' FILE

Specifying field separator

By default, awk uses space and tab as field separator. You can specify how fields are separated using the -F option.

$ awk -F "/" '{print $1}' FILE

Excluding columns

Print all the columns but not the 2 one:

$ awk '{$2=""; print $0}' FILE

Print all the columns but not 1 and 2:

$ awk '{$1=$2=""; print $0}' FILE