AWK tricks and hacks part 1

regular expression

AWK is pattern scanning and processing language. I Will show how useful is awk on some examples, in this part we will use “:” as a separator, we will use awk for select uniqe pattern from file and we will show how to take last word from line.

How to use : as a field separator

 awk -F : '{print $5}'

For example we can get comment from /etc/passwd for user wwwrun:

 
#
# grep -i wwwrun /etc/passwd
wwwrun:x:30:8:WWW daemon apache:/var/lib/wwwrun:/bin/false
#
#
# grep -i wwwrun /etc/passwd | awk -F : '{print $5}'
WWW daemon apache
#

Uniq without sort

 awk '!seen[$0]++'

Short example how to use it:

# cat test.txt
Thomas
Arnold
Lukas
Thomas
Peter
Thomas
Thomas
Lukas
Thomas
Arnold
#
# cat test.txt | awk '!seen[$0]++'
Thomas
Arnold
Lukas
Peter
#

Last word from line

 awk '{print $NF}'

We can select last name from the list of names even there are not the same number of names for person

# cat test.txt
Andrez Mercado
Leonor Gonzalez Mina
Ericson Alexander Molano
Jorge Onate
Elkin Ramirez
#
# cat test.txt | awk '{print $NF}'
Mercado
Mina
Molano
Onate
Ramirez
#

AWK tricks and hacks part 2

Leave a Reply