Ujjawal Khare
Ujjawal Khare

Reputation: 796

AWK: to sum colums and insert output in new row of csv file

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

Answers (2)

Aleks-Daniel Jakimenko-A.
Aleks-Daniel Jakimenko-A.

Reputation: 10653

Pure bash solution:

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

Kent
Kent

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

Related Questions