Differences between revisions 5 and 7 (spanning 2 versions)
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
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 16: Line 15:
x=0; while read -r NUMBER; do let x=x+"$NUMBER"; done < "myfile"; echo "$x" # One number per line.
sum
=0; while read -r line; do (( sum += line )); done < "myfile"; echo "$sum"
Line 18: Line 18:
{{{
# 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)