How to get total sum of all values of a data frame using awk

Viewed 94

Suppose I have a data frame like:

A,B,C,D
2,1,1,1
2,3,1,4

I want to get the total sum of the data frame, meaning that just a total value as an output. So for the given example, the output should be 15

I tried this but it gives sum for each column:

awk -F"," 'BEGIN {sum=0; OFS=","} {for (i=1; i<=NF; i++) a[i]+=$i } END {for (i in a) print a[i]}' file
3 Answers

could you please try following.

awk 'BEGIN{FS=","} FNR>1{for(i=1;i<=NF;i++){sum+=$i}} END{print sum}'  Input_file

What's not working in OP's approach: OP's logic is correct but we don't want to use array here, we need a simple variable which has all sum in it then in END block of code we need to print it.

Another approach :-)

awk -F',' 'NR>1{s=s FS$0}END{gsub(FS,"+",s);print "0"s}' file|bc

got 15

Related