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 !
Maybe the easier way to change field separator in awk is -F switch. For example:
$ awk -F: ‘{print $1}’ /etc/passwd
root
bin
…
miljan,
Thanks for your visit and for the hint ! I’ll add this in the post.
By the way, you have a very interesting blog !
Stephane
cut -d: -f1 /etc/passwd
root
daemon
bin
Nice site. awk is a real help.
I maintain a blog on unix commands, awk and sed one liners, its http://unstableme.blogspot.com/
//Jadu