Perform floating point arithmetic in shell script variable definitions

22,803

Solution 1

You may not want to use bc for this. Perhaps awk would work better:

awk '{sum+=$1};END{print sum/NR}' /path/to/file

Solution 2

As tagged , here is a bash 4.0 alternative to choroba's answer, to avoid wc and sed:

bash-4.2$ mapfile -t a < file

bash-4.2$ (IFS='+'; echo "(${a[*]})/${#a[@]}") | bc -l
1.24886080000000000000

Solution 3

I usually use bc for floating point arithmetics:

file=1.txt
echo '('$(<$file)')/'$(wc -l < $file) | sed 's/ /+/g' | bc -l
Share:
22,803

Related videos on Youtube

John B
Author by

John B

Updated on September 18, 2022

Comments

  • John B
    John B almost 2 years

    I understand bash and some other interpreters only perform arithmetic for integers. In the following for loop, how can I accomplish this? I've read that bc can be used but am not sure how to use bc in this situation.

    total=0
    for number in `cat /path/to/file`; do
            total=$(($total+$number))
    done
    average=$(($total/10))
    echo Average is $average
    

    file:

    1.143362
    1.193994
    1.210489
    1.210540
    1.227611
    1.243496
    1.260872
    1.276752
    1.294121
    1.427371
    
    • Hauke Laging
      Hauke Laging about 11 years
      Doesn't make sense to calculate the average in every round of the loop if only the last result is used, does it?
    • Stéphane Chazelas
      Stéphane Chazelas about 11 years
      ksh (ksh93) and zsh do do floating point arithmetics.
    • Palec
      Palec over 9 years
  • Hauke Laging
    Hauke Laging about 11 years
    @JohnB Then you should accept it as answer (i.e. click on the green check mark below the voting for my answer).
  • Hauke Laging
    Hauke Laging about 11 years
    If it's about bash I think this is much nicer: shopt -s extglob; value=...; value="${value%%*(0)}"; if [ -z "${value##*.}" ]; then value="${value}0"; fi; echo "$value". But for next time: I note your "Organizer" badge... 8-)
  • John B
    John B about 11 years
    For some reason, using sed in this solution caused $average to echo twice. I substituted with cut -c-9 and it fixed it. Have no clue why.
  • Bernhard
    Bernhard about 11 years
    @JohnB You should really try the awk alternative. Don't use bash for these kind of tasks!
  • chepner
    chepner about 11 years
    +1 Clever use of IFS!