Ask Ubuntu is a question and answer site for Ubuntu users and developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

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

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

Your Answer


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.