4

Since the following command using bc does not work for numbers in scientific notation, I was wondering about an alternative, e.g. using awk?

sum=$( IFS="+"; bc <<< "${arrValues[*]}" )
MaVe
  • 339
  • 4
  • 12

2 Answers2

5
sum=$(
  awk 'BEGIN {t=0; for (i in ARGV) t+=ARGV[i]; print t}' "${arrValues[@]}"
)

With zsh (in case you don't have to use bash), since it supports floating point numbers internally:

sum=$((${(j[+])arrValues}))

With ksh93:

If you need the kind of precision that bc provides, you could pre-process the numbers so that 12e23 is changed to (12*10^23):

sum=$(
  IFS=+
  sed 's/\([0-9.]*\)[eE]\([-+]*[0-9]*\)/(\1*10^\2)/g' <<< "${arrValues[*]}" |
    bc -l
)
Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
2

Perl solution:

perl -MList::Util=sum -l -e 'print sum(@ARGV)' -- "${array[@]}"

Or for arbitrary precision:

perl -Mbignum -MList::Util=sum -l -e 'print sum(0, @ARGV)' -- "${array[@]}"

(with a literal 0 added to force the sum to be made with bignums).

Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
choroba
  • 45,735
  • 7
  • 84
  • 110