bash divide result compared with float
-
22-10-2019 - |
سؤال
THis is part of my bash code;
b=`cat 101127_2_aa_1.fastq|head -$a|tail -1|sed 's/\(.\)B*$/\1/g'|wc -c`
d=`cat 101127_2_aa_1.fastq|head -$a|tail -1|wc -c`
if (($b%$d>=0.7))
then
HOwever I got problems like:
line 13: ((: 26%100>=0.7: syntax error: invalid arithmetic operator (error token is ".7")
WHat's the problem? thx
edit: Two if loops in my script:
if (($a%4==0))
if (( 10*$b/$d>= 7 ))
Seems for first one, only "%" works
And for the second one, only "/" works
I'm confused
المحلول
The division operator is /
, not %
.
Also bash does not have floats. The workaround is to do something like
if (( 10 * $b / $d >= 7 ))
or
if (( 10 * $b >= 7 * $d ))
نصائح أخرى
BASH is a typeless programming language without floating-point arithmetic. However, you can do flotaing-point operations by using the bc tool. Following article nicely explains how: http://www.linuxjournal.com/content/floating-point-math-bash . What you need from there is the float_cond()
function.
I would use awk
.
Here are some examples.
[jaypal:~] awk 'BEGIN{ print 44/3 }'
14.6667
[jaypal:~] a=55
[jaypal:~] b=4
[jaypal:~] awk 'BEGIN { print '$a'/'$b' }'
13.75
As suggested by @Amadan, we can do something like this completely in awk
-
a=44
b=5
c=$(awk 'BEGIN { print '$a'/'$b' }')
awk 'BEGIN{if ('$c'>.7) print "yeah"; else print "nope" }'