Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

How to get the sum of each column from file like:

123  32  122
43   11  0
444  112 32

and give the result as:

610 155 154

in a simple command?

It should be easy in Perl, but I'd like to know if someone had already packaged it in universe repository or somewhere else, along with other utilities to do with text tables.

share|improve this question
add comment

3 Answers 3

up vote 1 down vote accepted

This should do the trick:

cat foo | awk '{ SUM += $1; SUM1 += $2; SUM3 += $3} END { print SUM, SUM1, SUM3 }'

share|improve this answer
    
The column count is undetermined. –  Xiè Jìléi Jun 4 '11 at 2:18
add comment

awk is nice for these types of tasks

awk '{for (i=1; i<=NF; ++i) sum[i]+=$i} END {for (i=1; i<=NF; ++i) printf "%3d ", sum[i]; printf "\n"}' filename
share|improve this answer
add comment

In python:

reduce(lambda x, y: \
  map(lambda pair: pair[0] + pair[1], zip(x, y)), \
  [map(int, n.split()) for n in file("foo", "r").read().splitlines()])

where the number of columns and integer size is limited by available memory.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.