Reputation: 796
Hi I have a csv file with below data in it.
8/22/2013 1,417,196,108
8/23/2013 1,370,586,883
8/24/2013 1,362,561,606
8/25/2013 1,177,575,904
8/26/2013 1,228,394,403
8/27/2013 1,276,168,499
8/28/2013 1,265,333,615
I want a script that can help me to sum 2nd column and insert result in next row, so the output should look like:
8/22/2013 1,417,196,108
8/23/2013 1,370,586,883
8/24/2013 1,362,561,606
8/25/2013 1,177,575,904
8/26/2013 1,228,394,403
8/27/2013 1,276,168,499
8/28/2013 1,265,333,615
Total 9,097,817,018
Upvotes: 0
Views: 288
Reputation: 10653
#!/bin/bash
while read -r _ curNumber; do
(( answer += ${curNumber//,/} ))
done < file.csv
(( start = (${#answer} % 3 == 0 ? 3 : ${#answer} % 3) ))
echo -n "${answer:0:start}"
for ((i = start; i < ${#answer}; i += 3)); do
echo -n ",${answer:i:3}"
done
echo
Upvotes: 2
Reputation: 195079
the tricky part of this question is the thousand separator.
Try this line:
awk '{print;gsub(/,/,"");s+=$2}END{printf "Total %'\''d\n",s}' file
test with your data:
kent$ awk '{print;gsub(/,/,"");s+=$2}END{printf "Total %'\''d\n",s}' f
8/22/2013 1,417,196,108
8/23/2013 1,370,586,883
8/24/2013 1,362,561,606
8/25/2013 1,177,575,904
8/26/2013 1,228,394,403
8/27/2013 1,276,168,499
8/28/2013 1,265,333,615
Total 9,097,817,018
Upvotes: 3