Differences between revisions 4 and 5
Revision 4 as of 2011-06-24 12:48:10
Size: 463
Editor: 195
Comment: fix link
Revision 5 as of 2011-06-24 23:59:57
Size: 582
Editor: mavritivsx
Comment: Not sure if this is right, but I really wanted a _bash_ solution, not awk, and came up with this. -m
Deletions are marked like this. Additions are marked like this.
Line 12: Line 12:

----
'''BASH Alternative'''
{{{
x=0; while read -r NUMBER; do let x=x+"$NUMBER"; done < "myfile"; echo "$x"
}}}

How do I get the sum of all the numbers in a column?

This and all similar questions are best answered with an AWK one-liner.

awk '{sum += $1} END {print sum}' myfile

A small bit of effort can adapt this to most similar tasks (finding the average, skipping lines with the wrong number of fields, etc.).

For more examples of using awk, see handy one-liners for awk.


BASH Alternative

x=0; while read -r NUMBER; do let x=x+"$NUMBER"; done < "myfile"; echo "$x"

BashFAQ/076 (last edited 2011-06-25 15:19:06 by GreyCat)