This seems like a pretty popular question, but for some reason the awk solution I found here that I am trying does not work.
I have an alias that gets the info on some of my devices on my network. I want to be able to search the list and retrieve the device "name". The alias and output look like:
$ mtb devices
Alias Address Name Software Brand
------------------------------------------------------------
192.168.1.107 Device1 1009 Some_brand
TV 192.168.1.103 Device2 0831 Some_other_brand
TV2 192.168.1.105 Device3 0831 Some_brand
In my script, using grep I can take the line I am looking for, since I search by the ip address:
IP=$1
BOX=`mtb devices | grep ${IP}`
echo $BOX
This gives me a result:
$ ./my_devices.sh 192.168.1.105
TV2 192.168.1.105 Device3 0831 Some_brand
Now I want to get the "Name" from the line, so I used awk '{print $3}':
IP=$1
BOX=`mtb devices | grep ${IP} | awk '{print $3;}'`
echo $BOX
$ ./my_devices.sh 192.168.1.105
Device3
But when I search an IP address that does not have an alias, then I obviously get the wrong result:
$ ./my_devices.sh 192.168.1.107
1009
I looked for more soltions and I found another awk solution, but the new awk is not working:
IP=$1
BOX=`mtb devices | grep ${IP} | awk '{ for(i=1;i<=NF;i++) if ($i == "$IP") print $(i+1) }'`
echo $BOX
When I run my script it returns nothing:
$ ./my_devices.sh 192.168.1.105
$
Obviously I want it to return Device3
.
The IP address field and Name fields will always be populated, but the alias field may not be populated.