user3806232
user3806232

Reputation: 3

Using Awk to add hostname to line

I have this text file TopIP.txt: (fiction IPs and hostname)

Top destination for Source IP 1.2.3.4
    34322 2.3.4.5
    455   2.3.4.6

I want to add the hostname to each IP at the end of the line. My desire output is this:

Top destination for Source IP 1.2.3.4 hostname3.com
    34322 2.3.4.5 hostname1.com
    455   2.3.4.6 hostname2.com

I made it happen last week and didnt save and now i cant replicate it.

my code started something similar to this:

cat TopIP.txt | awk '{print $0, system("host " $NF)}'

Upvotes: 0

Views: 2144

Answers (2)

David C. Rankin
David C. Rankin

Reputation: 84569

You can also do it with sed easily:

sed -i "0,/IP/s/$/ `hostname -f`/" filename

That will simply add the current fully qualified hostname (hostname.domain.tld) to the end of the line containing IP. Before you use either, you need to check your networking config to insure either hostname -f or host ${!#} return the proper hostname. It is not uncommon for network configuration issues to cause invalid hostname returns.

Upvotes: 1

glenn jackman
glenn jackman

Reputation: 246877

I'd stick with bash:

while IFS= read -r line; do
    set -- $line
    echo "$line $(host ${!#})"
done < TopIP.txt > newfile

Upvotes: 3

Related Questions