Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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[*]}" )
share|improve this question
add comment

2 Answers 2

up vote 1 down vote accepted
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
)
share|improve this answer
    
@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
add comment

Perl solution:

perl -MList::Util=sum -l -e 'print sum(@ARGV)' "${array[@]}"
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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