4

How can I calculate the SUM for all the individual columns (115 Columns)?

Input.txt

1st,2nd,3rd,4th,5th,Till-115thColumn
51,34,27,67,88,99
56,39,32,72,93,104
66,49,42,82,103,114

Output.txt

1st,2nd,3rd,4th,5th,Till-115thColumn
173,122,101,221,284,317

I tried this command:

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

but I am not getting the required output.

2 Answers 2

11

This can be a way:

awk 'BEGIN{FS=OFS=","}
     NR==1{print}
     NR>1{for (i=1;i<=NF;i++) a[i]+=$i}
     END{for (i=1;i<=NF;i++) printf a[i] OFS; printf "\n"}' file

It sets the comma as input/output field separator and then stores the sum of each column in an array a[]. Finally, it loops through the results and prints them. Note NR==1 is user to print the header.

For your given input it returns:

$ awk 'BEGIN{FS=OFS=","} NR==1{print} NR>1{for (i=1;i<=NF;i++) a[i]+=$i} END{for (i=1;i<=NF;i++) printf a[i] OFS; printf "\n"}' file
1st,2nd,3rd,4th,5th,Till-115thColumn
173,122,101,221,284,317,

Why wasn't your script working?

Because you missed a ; in the for declaration:

awk -F"," 'BEGIN {sum=0; OFS=","} {for (i=1 i<=NF; i++) a[i]+=$i } END {for (i in a) print a[i]}' a
awk: line 1: syntax error at or near )

so this makes it:

$ awk -F"," 'BEGIN {sum=0; OFS=","} {for (i=1; i<=NF; i++) a[i]+=$i } END {for (i in a) print a[i]}' file
                                             ^
174
124
104
225
289
317
Sign up to request clarification or add additional context in comments.

Comments

3

your codes did the calculation correctly, but has problem in output part:

awk -F, '{for(i=1;i<=NF;i++)a[i]+=$i}
        END{for(i=1;i<=NF;i++)printf "%d%s", a[i], (i==NF?"\n":",")}'file

3 Comments

I really like the trick not to have a trailing comma and have a new line at the end. Good one!
+1 for seeing the ternary beauty with coffee in the morning.
while using cygwin, last 2 columns "SUM-Output" is not coming , any idea ?/cygdrive/g $ cat Input.txt a1st,b2nd,c3rd,d4th,e5th,Till-115th 51,34,27,67,88,99 56,39,32,72,93,104 66,49,42,82,103,114 /cygdrive/g $ awk 'BEGIN{FS=OFS=","} NR==1{print} NR>1{for (i=1;i<=NF;i++) a[i]+=$i} END{for (i=1;i<=NR;i++) printf a[i] OFS; printf "\n"}' Input.txt a1st,b2nd,c3rd,d4th,e5th,Till-115th 173,122,101,221,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.