Getting a specific field of a line with awk is really simple. For example :
spaghetti% echo "test1 test2 test3" | awk '{print $2}'
test2
A more “real life” example is as following, which will find in /etc/hosts the IP address of localhost (pick another host if you wish
) :
spaghetti% cat /etc/hosts | awk '/localhost/ { print $1;}'
127.0.0.1
::1
If the field separator is not a space, awk will let you change it with the FS variable :
spaghetti% echo "test1:test2:test3" | awk 'BEGIN { FS = ":"} { print $2 }'
test2
This should be enough to get you started !
Note : As suggested by Miljan, there’s a much simpler way to change the Field Separator : the -F option switch. So the example I provided can be rewritten as follows :
spaghetti% echo "test1:test2:test3" | awk -F: '{ print $2 }'
test2
Cool. Thanks Miljan !