Monday, March 24, 2008

Compute simple average using AWK


Sample files:

$ cat file1.txt

AA 33
BB 21
KK 99
CC 14
DD 13

$ cat file2.txt
EE 32
FF 45
FG 56
KK 99
FF 67

Objective:
- Item "KK" is erroneous, so should not be considered in average
- Compute the average of rest of the Items 2nd fields considering both the files, file1.txt and file2.txt.

The script:
$ awk '
!/^KK/ {sum+=$2; ++n; print $1,$2 }
END { print "-----------"
print "Tot="sum"("n")";print "Avg="sum"/"n"="sum/n}
' file1.txt file2.txt

Output:
AA 33
BB 21
CC 14
DD 13
EE 32
FF 45
FG 56
FF 67
-----------
Tot=281(8)
Avg=281/8=35.125

2 comments:

Random Guy said...

thanks.. u r doing a great job.. :-)

Unknown said...

@Sharat, thanks, keep in touch.

© Jadu Saikia www.UNIXCL.com