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 bash, 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
Related videos on Youtube
Author by
John B
Updated on September 18, 2022Comments
-
John B almost 2 years
I understand
bash
and some other interpreters only perform arithmetic for integers. In the followingfor
loop, how can I accomplish this? I've read thatbc
can be used but am not sure how to usebc
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 about 11 yearsDoesn'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 about 11 years
ksh
(ksh93) andzsh
do do floating point arithmetics. -
Palec over 9 yearsSame question on Stack Overflow: Floating-point arithmetic in UNIX shell script
-
-
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 about 11 yearsIf 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 about 11 yearsFor some reason, using
sed
in this solution caused $average to echo twice. I substituted withcut -c-9
and it fixed it. Have no clue why. -
Bernhard about 11 years@JohnB You should really try the
awk
alternative. Don't usebash
for these kind of tasks! -
chepner about 11 years+1 Clever use of
IFS
!