所有列的所有行的总和-Bash [英] Sum of all rows of all columns - Bash

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

问题描述

我有一个像这样的文件

1 4 7 ...
2 5 8
3 6 9 

我想将其作为输出

6 15 24 ...

这是所有列的所有行的总和.我知道将某一列(例如第1列)的所有行加起来,您可以这样做:

That is the sum of all the lines for all the columns. I know that to sum all the lines of a certain column (say column 1) you can do like this:

awk '{sum+=$1;}END{print $1}' infile > outfile

但是我不能为所有列自动做到这一点.

But I can't do it automatically for all the columns.

推荐答案

echo "1 4 7
2 5 8
3 6 9 " \
| awk '{for (i=1;i<=NF;i++){
   sums[i]+=$i;maxi=i}
 }
 END{
   for(i=1;i<=maxi;i++){
     printf("%s ", sums[i])
   }
 print}'

输出

6 15 24

我的回忆是,您不能依靠for (i in sums)来生成任何特定顺序的密钥,但是在更高版本的gawk中,这也许是固定的".

My recollection is that you can't rely on for (i in sums) to produce the keys any particular order, but maybe this is "fixed" in newer versions of gawk.

如果您使用的是老式Unix awk,则此解决方案将使您的输出保持相同的列顺序,而不管文件的宽度如何.

In case you're using an old-line Unix awk, this solution will keep your output in the same column order, regardless of how "wide" your file is.

IHTH

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

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