Monday, May 14, 2007

Some important tasks using AWK


Here I am discussing some tasks using AWK.

Task 1: Finding "Average size" of files

$ ls -l
total 12
-rw-r--r-- 1 jsaikia staff 500 Dec 13 17:01 as.cc
-rw-r--r-- 1 jsaikia staff 1980 Dec 13 17:02 bs.cc
-rw-r--r-- 1 jsaikia staff 2880 Dec 13 17:02 cs.cc

$ ls -l | awk 'NF!=1 {total+=$5} END {print "Avg: "total/(NR-1)}'
Avg: 1786.67

Task 2: Generating Fibonacci series
$ awk 'BEGIN{p=1;q=1; while(++x<=10){print p;t=p;p=p+q;q=t};exit;}'
1
2
3
5
8
13
21
34
55
89

Task 3: Counting Number of effective lines in a file
$ cat my.out (It got two blank lines)
line 1

line 2

line3
$ awk 'NF !=0 {++count}END {print count}' my.out
3

$ wc -l my.out (this prints 5)
5 my.out

An alternative would be
$ cat my.out | grep -vc '^$'
3

Task4: Count based upon condition
Suppose the following file is an output of an application. The format of the file contents is

Name|Age|Points|Born Place|Currently

$ cat my.out
Hemen|23|20000|bangalore|bangalore
Esh|24|21345|bangalore|china
Nill|20|12321|miami|bangalore
Chen|34|34321|china|china

$ awk -F "|" '$NF=="bangalore" {++c} END {print "Number of person who are presently in bangalore = " c}' my.out
Number of person who are presently in bangalore = 2

Task5: Reverse the words in a line

$ echo "I love shell scripting" | awk '{for (j=NF;j>0;j--) {printf "%s ", $j}}'
scripting shell love I

No comments:

© Jadu Saikia www.UNIXCL.com