awk总和多列

时间:2014-02-26 13:08:25

标签: awk

如何计算所有单个列(115列)的SUM?

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

我试过这个命令:

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

但我没有得到所需的输出。

2 个答案:

答案 0 :(得分:11)

这可以是一种方式:

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

它将逗号设置为输入/输出字段分隔符,然后将每列的总和存储在数组a[]中。最后,它遍历结果并打印出来。注意NR==1是用户打印标题。

对于您的给定输入,它返回:

$ 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,

为什么你的脚本没有工作?

因为您错过了;声明中的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 )

所以这就是:

$ 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

答案 1 :(得分:3)

您的代码正确进行了计算,但输出部分存在问题:

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