## 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

#### 1 comment:

Unknown said...

< details.txt perl -F'\|' -pale '
\$a=0;\$_ = join \$", map { \$a++ < 1 ? "[\$_]" : s/^-/_/r } @F
' |
dc -e "
[2k]s# [0kdl.%0!=#]s%
[q]sq [124a]s| [[]pq]s\$
[d z2- ;x + z2- :x]s+ [z 1 <+ SM z 0 <s]ss
[LMn li1-dsi 0 =\$ l|xn li 0 <P]sP
[? z 0 =q l.1+s. zsF lsx lFsilPx c l?x]s?
[li1-dsi ;x SM li 1 <S]sS
[li1-dsi ;x l%xl./0k SM li 1 <A]sA
0s.l?x
[------------------]pc
lFsilSx
[total]SM
lFsilPx
lFsilAx
[Avrg.]SM
lFsilPx
"