AWK总结多列 [英] awk sum multiple columns

查看:181
本文介绍了AWK总结多列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何计算总和所有单个列(115列)?

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

INPUT.TXT

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的

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.

推荐答案

这可能是一种方式:

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 为用户打印头。

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,

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

由于你错过了一个; 声明:

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

这篇关于AWK总结多列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆