Monday, September 8, 2008

Calculate sum and average of multiple lines - awk in bash


Input file:

$
cat details.txt
line1|5002|1200|90
line2|3002|4200|80
line3|5052|1600|90
line4|2006|3260|10

Required: Calculate and print the sum and averages of each fields in all the lines of details.txt

$ awk 'BEGIN {FS=OFS="|"} { print; for (i=2; i<=NF; ++i) sum[i] += $i; j=NF }
END { printf "%s%s", "------------------", "\ntotal"; for (i=2; i <= j; ++i) printf "%s%s", OFS, sum[i]; printf "\n"; }' details.txt

Output:
line1|5002|1200|90
line2|3002|4200|80
line3|5052|1600|90
line4|2006|3260|10
------------------
total|15062|10260|270

$ awk 'BEGIN {FS=OFS="|"} { print; for (i=2; i<=NF; ++i) sum[i] += $i; j=NF }
END { printf "%s%s", "------------------", "\nAvg"; for (i=2; i <= j; ++i) printf "%s%s", OFS, sum[i]/NR; printf "\n"; }' details.txt

Output:
line1|5002|1200|90
line2|3002|4200|80
line3|5052|1600|90
line4|2006|3260|10
------------------
Avg|3765.5|2565|67.5

No comments:

© Jadu Saikia www.UNIXCL.com