Differences between revisions 3 and 7 (spanning 4 versions)
Revision 3 as of 2008-11-22 16:45:30
Size: 482
Editor: GreyCat
Comment: formatting change
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 11: Line 11:
For more examples of using {{{awk}}}, see [[http://www.student.northpark.edu/pemente/awk/awk1line.txt|handy one-liners for awk]]. For more examples of using {{{awk}}}, see [[http://www.pement.org/awk/awk1line.txt|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.
}}}

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)