summing contents of a field - bash
I have a file that contains data in the following format:
Field 1 Field 2 nCalls duration
My task is to sum the nCalls and dur开发者_运维问答ation fields. The code I have written so far is as follows:
cat ${file} |\
while read n1 n2 nCalls nDuration
do
#sumCalls=$((${sumCalls} + ${nCalls}))
#sumDuration=$((${sumDuration} + ${nDuration}))
sumCalls=`expr ${sumCalls} + ${nCalls}`
sumDuration=`expr ${sumDuration} + ${nDuration}`
echo "${sumCalls} ${sumDuration}"
echo -n "${appName} ${sumCalls} ${sumDuration}" > temp.txt
done
tail -n1 temp.txt >> ${outFile}
Both the statements above do not work. I get syntax errors.
My question is:
1. Where am I going wrong with the above code? 2. Is there a better way to do this than write into and out of files?Thanks,
SriramThis is what awk
was built for:
cat ${file} | awk '{c = c + $3; d = d + $4} END {print "APPNAME", c, d}'
The following transcript shows it in action:
pax$ export appName=xyz
pax$ echo 'a b 1 2
...> a b 3 4
...> a b 5 6' | awk -vAPPNAME=${appName} '{c=c+$3;d=d+$4}END{print APPNAME,c,d}'
xyz 9 12
A Ruby(1.9+) example
$ ruby -ane 'BEGIN{c=d=0};c+=$F[2].to_i;d+=$F[3].to_i;END{puts "APPNAME, #{c},#{d}"}' file
As already said, right tool would be awk.
To the errors: The code is fine and runs (esp both expressions). Possible errors:
- You dont initialize your sum up variables to 0 (if they have already value than it could yield wrong results.
- If your file contains more than 4 columns, your read behaves different: Read assigns the last passed value always the rest of the line! I.e. your last variable gets with a 5 column entry 2 space seperated values assigned => and here expr can give a syntax error. Solution for this: Add to the line a 5 variable REST. With 4 columns it stays empty, with more it catches up the rest.
精彩评论