Roberto Santana Roberto Santana - 2 months ago 21
Linux Question

Add calculated column at the end of command result

I want to get a list with those fields in just a command:

IP[TAB]MAC[TAB]VENDOR[TAB]HOSTNAME


This is the result that I'd like to have:

192.168.1.1[TAB]54:a0:50:xx:xx:xx[TAB]ASUSTek COMPUTER INC.[TAB]Router
192.168.1.2[TAB]60:33:4b:xx:xx:xx[TAB]Apple, Inc.[TAB]iMac-John
192.168.1.52[TAB]08:ed:b9:xx:xx:xx[TAB]Apple, Inc.[TAB]iMac-Peter
192.168.1.26[TAB]c0:11:73:xx:xx:xx[TAB]Samsung Electronics Co.,Ltd[TAB]Erik's Android


I can get the three first columns easily with this command:

sudo arp-scan -l | tail -n +3 | head -n -3


Result:

192.168.1.1[TAB]54:a0:50:xx:xx:xx[TAB]ASUSTek COMPUTER INC.
192.168.1.2[TAB]60:33:4b:xx:xx:xx[TAB]Apple, Inc.
192.168.1.52[TAB]08:ed:b9:xx:xx:xx[TAB]Apple, Inc.
192.168.1.26[TAB]c0:11:73:xx:xx:xx[TAB]Samsung Electronics Co.,Ltd


The problem is to add the 4th column, I'm trying to do it with
awk
command but I get the result in a new line instead of the format I like.

sudo arp-scan -l | tail -n +3 | head -n -3 | awk -F '\t' '{ print $0 system("getent hosts " $1) }'


Unexpected result:

192.168.1.1[TAB]Router
192.168.1.1[TAB]54:a0:50:xx:xx:xx[TAB]ASUSTek COMPUTER INC.
192.168.1.2[TAB]iMac-John
192.168.1.2[TAB]60:33:4b:xx:xx:xx[TAB]Apple, Inc.
192.168.1.52[TAB]iMac-Peter
192.168.1.52[TAB]08:ed:b9:xx:xx:xx[TAB]Apple, Inc.
192.168.1.26[TAB]Erik's Android
192.168.1.26[TAB]c0:11:73:xx:xx:xx[TAB]Samsung Electronics Co.,Ltd


Any help will be appreciated!

Answer

The correct syntax for your current awk command is:

awk 'BEGIN { FS=OFS="\t" }
{
    cmd="getent hosts \"" $1 "\""
    $0 = $0 FS ( (cmd | getline line) > 0 ? line : "N/A" )
}1'

but you definitely don't need the tail since you could just do NR>2{...} in awk and there's a good chance you don't need the head either but without seeing the raw arp-scan output we can only guess.

Also - if this is all you're doing with awk then you should probably be using shell instead:

while IFS=$'\t' read -r ip rest; do
    printf '%s\t%s\t%s\n' "$ip" "$rest" $(getent hosts "$ip")
done
Comments