Saturday, December 19, 2009

Sum numbers in each row - awk

Input file contains the scores of few students in certain rounds of a game in the following format.

id,Name,score1,score2,score3 etc

\$ cat file.txt
id9,Mohit Kishore,19,13,14,10
id2,Niraj Kumar,13,8,23,8
id8,Kate Nil,19,18,15
id4,Rashi S,19,28,65,10,19

Required output:

Calculate the sum and average score of each student (notice that the number of rounds played by each student is not constant, few played 3 rounds, few 4 etc)

The awk script:

\$ awk '
BEGIN {FS=OFS=","}
{
sum=0; n=0
for(i=3;i<=NF;i++)
{sum+=\$i; ++n}
print \$0,"sum:"sum,"count:"n,"avg:"sum/n
}' file.txt

Output:

id9,Mohit Kishore,19,13,14,10,sum:56,count:4,avg:14
id2,Niraj Kumar,13,8,23,8,sum:52,count:4,avg:13
id8,Kate Nil,19,18,15,sum:52,count:3,avg:17.3333
id4,Rashi S,19,28,65,10,19,sum:141,count:5,avg:28.2

Related posts:

- Calculate sum and average of multiple lines - bash
- Sum of numbers in a file - UNIX
- Calculate percentage using awk in bash
- Compute simple average using awk in bash
- Calculate sum of two times of hh-mm-ss format using awk
- Compute sum with awk substr function

Karan Bohra said...

while IFS= read -r Line
do
IFS=","; set -f; set -- \$Line;
last=
while :
do
case \$1 in
'' | *[!0-9]* ) shift;;
* )
N=\$#
S=0
while case \$# in 0 ) unset last; break;; esac
do
S=`expr \$S + \$1`
shift
done;;
esac
\${last+:} break
done
A=`expr \$S / \$N`
echo "\$Line,sum:\$S,count:\$N,avg:\$A"
done

Karan Bohra said...

while IFS= read -r line
do
stack=\$(printf '[%s]%s\n' "\$line" "\$(echo "\$line" | cut -d, -f3- | tr ',-' ' _')
dc -e "
[1-]sa
[+z3!>b]sb
\$stack
zlaxsc
lbxsd
n[,sum:]nldn[,count:]nlcn[,avg:]nldlc/p
"
done < file.txt