If you work with data, very likely you deal with files with numbers. You may want a quick way to sum up a column of numbers in a shell. Here is the guide with examples.
Before the summation, you may want to take a look at the data. Awk would be helpful (for details, see Using awk in Bash: A Guide with Examples). The example command below displayed the second column ($2) of file.csv, which is comma delimited (-F,).
awk -F, '{print $2}' file.csv
If the file is very big, you may combine with more, head or tail.
Let’s do the summation. Seven methods for adding up numbers (both integers or decimal numbers) are listed below.
1 Awk
awk -F, '{print $2}' file.csv | awk '{s+=$1} END {print s}'
2 Python
Note: replace ‘pytho n’ by ‘python’. There is a bug in the browser that did not allow ‘python’.
awk -F, '{print $2}' file.csv | pytho n -c "import sys; print(sum(float(l) for l in sys.stdin))
3 jq
awk -F, '{print $2}' file.csv | jq -s 'add'
4 while-loop
s=0; while read num; do ((s += num)); done < <(awk -F, '{print $2}' file.csv); echo $s
5 dc
dc -f <(awk -F, '{print $2}' file.csv) -e '[+z1<r]srz1<rp'
6 perl
perl -lne '$x += $_; END { print $x; }' < <(awk -F, '{print $2}' file.csv)
7 echo
f=$(awk -F, '{print $2}' file.csv); echo $(( ${f//$'\n'/+} ))