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[*]}" )
0
4
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
)
1
  • @MaVe, the + character is not special to the shell and doesn't need quoted (quoting won't harm though). – Stéphane Chazelas Nov 6 '13 at 22:26
2

Perl solution:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.