awk : one-liner to select a field

Getting a specific field of a line with awk is really simple. For example :
spaghetti% echo "test1 test2 test3" | awk '{print $2}'

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;}'

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 }'

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 }'

Cool. Thanks Miljan !

4 thoughts on “awk : one-liner to select a field”

  1. Maybe the easier way to change field separator in awk is -F switch. For example:

    $ awk -F: ‘{print $1}’ /etc/passwd

Comments are closed.