Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
711 views
in Technique[技术] by (71.8m points)

awk - Sum of all rows of all columns - Bash

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 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There is a very simple command called numsum to do this:

numsum -c FileName

-c   ---    Print out the sum of each column.

For example:

cat FileName
1 4 7 
2 5 8
3 6 9 

Output :

numsum -c FileName
6 15 24

Note: If the command is not installed in your system, you can do it with this command:

apt-get install num-utils

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...