Who will win the election? – Part 2 – AWK
I was surfing the web today here and there when suddenly I stumbled upon a page in The Geek Stuff which explained a shell command called awk. It’s a great tool to search through a text file for a pattern. The site contained many easy to understand examples on the usage of awk.
The basic syntax is:
awk '/search pattern 1/ {actions1}
/search pattern 2/ {actions2}' filename
Here, actions1 is activated when the search pattern 1 is found and actions2 when search pattern 2 is found. The data is taken from filename.
This command can be manipulated in various ways to achieve many complex tasks in easily. The thought that instantly came to my mind was the Who will win the election script I wrote in the previous blog post. In that, the scripts creates a file named results which will store the results of the poll. An example of a results file is as follows:
MR tham MR sand SF hugo MR bosh SF dialz
Here, three people (tham, sand and bosh) think that MR will win the election and the other two think that SF will win. Okay, that script we wrote the last time creates this file, but how can we get a summary of the results after the poll? We want to know how many voted for MR and SF respectively.
AWK comes to the rescue. Here’s a script to count the number of votes for MR and SF and display them:
#!/bin/bash
#: Description: Gives a summary of the results of Who Will Win
the Election?
awk 'BEGIN { mr=0;sf=0; }
$1 ~ /MR/ { mr++; }
/SF/ { sf++; }
END {print "MR =",mr,"\nSF =",sf;}' results
It’s just one command! The output for the results file given above will be as follows:
MR = 3 SF = 2
Seems awk is a great tool to manipulate text files. For more info on awk visit this page.
So bye for now! See ya next time with another script!
Filed under: Uncategorized | 1 Comment

keep it up