Sum of all rows of all columns - Bash

后端 未结 6 470
鱼传尺愫
鱼传尺愫 2021-01-20 02:54

I have a file like this

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

And I would like to have as output

6 15 24 ...

That is the

6条回答
  •  Happy的楠姐
    2021-01-20 03:49

    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}'
    

    output

    6 15 24
    

    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.

    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

提交回复
热议问题