Bash Scientific Notation

Hello there,

I have a script that must be written in bash that has to deal with reading in values from a file (in scientific notation), and requires executing some mathematical operations with them. What is the easiest way to go about doing this/converting it to float to use | bc, etc.?

Thanks!

This should be a basic example:

a=65; b=1.11; c=30 ; echo "scale= $a; $b ^ $c" | bc

For anything else try to elaborate your request.

I think the main problem here is the "scientific notation". I guess you mean numbers like 1.234e29 which are not supported by bc either?

Maybe something like this ...?

echo "1.234e23 9.876e14" | sed -e 's/ /*/' | perl -nle 'print eval $_'

Concur with danmero, an example of the input and expected output would help.

bc can do the job

echo "1.234e23 9.876e14" | sed 's/e/*10^/g;s/ /*/' | bc

Good catch; thanks for the correction.

Or just awk:

awk -v a="1.234e23" -v b="9.876e14" 'BEGIN{print (a * b)}'

Thanks all, in case you are interested -- I ended up using sed:

floatVar1=$(echo $Var1 | sed 's/\([0-9]*\(\.[0-9]*\)\?\)[eE]+\?\(-\?[0-9]*\)/(\1*10^\3)/g;s/^/scale=30;/'| bc)

There are some difficulties with the specific scientific notation my data files were using. (having an extra + after the E, 1.00e+1 = 10), so I had trouble getting bc to work, but I may have just messed up. However, the idea behind the question was supposed to be specifically how to convert something from scientific notation to float. Sorry for the confusion.

One of the reasons I suggested Perl was that it can cope with a reasonable set of variations like that.