awk is quite useful when you need to filter your output. As a start I will demonstrate a simple usage of awk.

As we all know every unix/linux have /etc/passwd file, which contains the user’s information like username,user id, home directory, gecos / real name information etc. For this example I will show you how awk can grab some information from /etc/passwd file.

admin# cat /etc/passwd
john:x:3001:3000:John Albert Jr:/home/john:/bin/bash
andrew:x:3002:3000:Andrew Wong:/home/andrew:/bin/bash
william:x:3003:3000:William Wallace:/home/william:/bin/bash
sulaiman:x:3004:3000:Sulaiman Ahmad:/home/sulaiman:/bin/bash

lets assume we have the above /etc/passwd file, and a simplest example will be to grab username and the home directory of each user.

admin# cat /etc/passwd | awk -F: '{print $1 $6}'
john /home/john
andrew /home/andrew
william /home/william
sulaiman /home/sulaiman
admin#

The output is very simple. In above example awk was used with option -F: which will treat : as a delimeter to separate the values of every lines in /etc/passwd. With the : as a delimeter/separator, we now have separated every line into 7 unit, the first unit will be known as $1, then second as $2, and so on until the last unit $7. In the above example $1 is the username and $6 is the user’s home directory.

If you know C programming language then you sure knows the function printf(), where you can do some simple formatting to the output. The good news is awk can use the printf() function. Lets see some example:

admin# cat /etc/passwd | awk -F: '{printf("%s has a home at %s\n",$1,$6)}'
john has a home at /home/john
andrew has a home at /home/andrew
william has a home at /home/william
sulaiman has a home at /home/sulaiman
admin#

As we have learned about for loop in previous article, we can actually apply it here with awk this time. Lets do some simple user’s home storage calculation:

admin# env | grep SHELL
SHELL=/bin/bash
admin# for i in `cat /etc/passwd | awk -F: '{print $6}' `
> do
> du -ks $i
> done
332440 /home/john
24550 /home/andrew
10220 /home/william
250556 /home/sulaiman
admin#

Happy exploring, in the future article we will see more usage of awk.

Note: in awk the single quote IS the normal single quote (unlike the single quote in the for loop)

Tags: , , ,

Leave a Reply

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>