Monday, May 01, 2006

awk tip: simple looping and counting

This blog on "awk" could be very useful for manipulating numbers over simple filters in unix. If this is too obvious for some of you, put in some more tips over the comments section and that will be of great help to the rest of us. I am going to illustrate the use of awk in counting with a simple example. Let us say that the following file "test.txt" contains the expenses of different groups in a company.

> cat test.txt

10 X-group
30 X-group
20 Y-group
22 Z-group
23 X-group

If I wanted to count the expenses of group 'X' , I need to pick up the values of group X and then add them. Instead of writing scripts to do the job, awk can be used effectively to finish the job easily.

> grep "X-group" test.txt | awk 'BEGIN{s=0}{s+=$1}END{print s}'

63

will count the expenses due to group X alone. The "BEGIN" and "END" constructs have been used to start a loop over the group "X" and to count the total sum spent on X.

No comments: