Awk sum several columns

How can I calculate the SUM for all 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 do not get the desired result.

+4
source share
2 answers

It could 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 an I / O field separator, and then stores the sum of each column in the array a[]. Finally, he looks through the results and prints them. Note NR==1- this is the user to print the title.

For this 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 didn't your script work?

Since you missed ;in the ad for:

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 )

therefore it does:

$ 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
+10
source

your codes calculated correctly, but the problem is in the 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
+2

Source: https://habr.com/ru/post/1528962/


All Articles