Differences between revisions 6 and 7
Revision 6 as of 2011-06-25 05:48:53
Size: 1154
Editor: Lhunath
Comment: expand on the bash example.
Revision 7 as of 2011-06-25 15:19:06
Size: 1173
Editor: GreyCat
Comment: formatting
Deletions are marked like this. Additions are marked like this.
Line 13: Line 13:
----
'''
BASH Alternative'''
=== BASH Alternatives ===
Line 18: Line 17:
}}}
{{{
Line 20: Line 21:
}}}
{{{
Line 22: Line 25:

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 Alternatives

# One number per line.
sum=0; while read -r line; do (( sum += line )); done < "myfile"; echo "$sum"

# Add numbers in field 3.
sum=0; while read -r -a fields; do (( sum += ${fields[2]} )); done < "myfile"; echo "$sum"

# Do the same for a file where the rows are not lines but separated by semicolons, and fields are comma delimited.
sum=0; while IFS=, read -rd ';' -a fields; do (( sum += ${fields[2]} )); done < "myfile"; echo "$sum"

# Note that for the above, the file needs to end with a ; (not end with a row).  If it doesn't, you can replace ''< "myfile"'' by ''<<< "$(<myfile);"'' to add the semicolon so ''read'' can see the last row.

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