Bash can't deal with decimals but it can handle simple manipulation of integers, you just need to use a trick like process substitution to make the variable accessible outside the loop:
n=0;while read i; do let n+=$i; done < <(awk '{print $1}' foo); echo $n;
or
n=0;while read i; do n=$((n+i)); done < <(awk '{print $1}' foo); echo $n;
The n=0
is there just to make sure that $n
is always 0, otherwise, running these commands a second time would return 252 instead of 126.
While the most straightforward way would be to use gawk
to make the calculation, you could also use a Perl one-liner:
awk '{print $1}' foo | perl -lne '$k+=$_;END{print "$k"};'
The -l
flag removes newlines (chomp
) and adds one to the end of each printed string, the -n
means read the file line by line, saving each line as $_
and run the script provided with -e
.
Or do the whole thing in Perl:
perl -alne '$k+=$F[0];END{print "$k"};' foo
The -a
flag for Perl turns on automatic line splitting (like gawk
). By default, fields are split on spaces but that can be changed using -F
. The resulting fields are saved as the @F
array so the 1st field is $F[0]
.