Licence
Creative Commons License

This work by Stephane KATTOOR is licensed under a Creative Commons Attribution 3.0 Unported License.
Feeling like tipping ?
If you find this blog useful, you might consider sending a few bitcoins to support it : 1BTtsC3beGJ6ysd8DhrXjdo6jVw5WD9mvY
RSS
 
RSS Feed
Follow me !
Tech@Sakana on Facebook
Search this site

Newsletter

Get latest posts by email (No spam, only posts):

Enter your email address:

Delivered by FeedBurner

Categories
Monthly archives
October 2007
M T W T F S S
« Sep   Nov »
1234567
891011121314
15161718192021
22232425262728
293031  
Day: für den 27. October 2007
awk : one-liner to select a field - October 27, 2007 by Stephane Kattoor

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 !

Who am I ?
Ads