Sum of all rows of all columns - Bash

后端 未结 6 410
鱼传尺愫
鱼传尺愫 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条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-20 03:55

    You want to sum every column differently. Hence, you need an array, not a scalar:

    $ awk '{for (i=1;i<=NF;i++) sum[i]+=$i} END{for (i in sum) print sum[i]}' file
    6
    15
    24
    

    This stores sum[column] and finally prints it.

    To have the output in the same line, use:

    $ awk '{for (i=1;i<=NF;i++) sum[i]+=$i} END{for (i in sum) printf "%d%s", sum[i], (i==NF?"\n":" ")}' file
    6 15 24
    

    This uses the trick printf "%d%s", sum[i], (i==NF?"\n":" "): print the digit + a character. If we are in the last field, let this char be new line; otherwise, just a space.

提交回复
热议问题