how to divide and multiply variables inside quote marks - bash

I am trying to get a result of percentage with the following;
for FNAME in *_1.fq
do
FILE=${FNAME##*/}
SAMPLE=${FILE%_1.fq}
echo "processing ${SAMPLE}"
let "Raw_reads = $((`cat ${SAMPLE}_1.fq | wc -l` / 4)) + $((`cat ${SAMPLE}_2.fq | wc -l` / 4))"
let "Error_corrected = $((`cat unfixrm_${SAMPLE}_1.cor.fq | wc -l` / 4)) + $((`cat unfixrm_${SAMPLE}_2.cor.fq | wc -l` / 4))"
let "Error_corrected_per = ($Error_corrected / $Raw_reads) * 100"
echo -e "$SAMPLE\t$Raw_reads\t$Error_corrected($Error_corrected_per%)"
done
I get this result; how do I get (44%) and (20%)
processing FB_0d
FB_0d 100 44(0%)
processing FB_2d
FB_2d 200 40(0%)

Since, i.e., 44/200 equals 0 in integer arithmetic, and multiplying 0 with anything also results in 0, I suggest the following alternatives:
Either do, in your formula, multiplication by 100 first, and division last, i.e.
((Error_corrected_per = (Error_corrected * 100) / Raw_reads))
Another possibility (if this is an option for you) would be to rewrite your program in, for instance, zsh instead of bash, where you have floating point arithmetic.

Related

Syntax error on bash shell trying to perform a simple calculation

I'm having a syntax error ((standard_in): syntax error)on 3rd and 5th line.
#!/bin/bash
i=`echo "8.8007751822"|bc`
rws = `echo "0.49237251092*$i" |bc`
rmt = `echo "0.85 * $rws"| bc`
dx = `echo "log ($rws / 0.000001) / 720.0" | bc`;
Can anyone help me?
A few things:
Assignments must not have blanks around the =
i=`echo "8.8007751822"|bc` is a really complicated way to write i=8.8007751822
bc has no function log, there's only l for the natural logarithm (and l requires the -l option to be enabled)
I would move everything into bc instead of calling it multiple times:
bc -l <<'EOF'
i = 8.8007751822
rws = i * 0.49237251092
rmt = 0.85 * rws
dx = (l(rws / 0.000001) / l(10)) / 720
dx
EOF
This prints the value of dx.

How to calculate percentage in shell script

I used the below line of script in my shell code
Percent=echo "scale=2; $DP*100/$SDC" | bc
it returns .16 as output but i need it as 0.16
Posix-compliant solution using bc:
#!/bin/sh
Percent="$(echo "
scale=2;
a = $DP * 100 / $SDC;
if (a > -1 && a < 0) { print "'"-0"'"; a*=-1; }
else if (a < 1 && a > 0) print 0;
a" | bc)"
That's kind of ugly with all of those special checks for cases when the answer is between -1 and 1 (exclusive) but not zero.
Let's use this Posix-compliant solution using awk instead:
#!/bin/sh
Percent="$(echo "$DP" "$SDC" |awk '{printf "%.2f", $1 * 100 / $2}')"
Z shell can do this natively:
#!/bin/zsh
Percent="$(printf %.2f $(( DP * 100. / SDC )) )"
(The dot is necessary to instruct zsh to use floating point math.)
Native Posix solution using string manipulation (assumes integer inputs):
#!/bin/sh
# # e.g. round down e.g. round up
# # DP=1 SDC=3 DP=2 SDC=3
Percent=$(( DP * 100000 / SDC + 5)) # Percent=33338 Percent=66671
Whole=${Percent%???} # Whole=33 Whole=66
Percent=${Percent#$Whole} # Percent=338 Percent=671
Percent=$Whole.${Percent%?} # Percent=33.33 Percent=66.67
This calculates 1,000 times the desired answer so that we have all the data we need for the final resolution to the hundredths. It adds five so we can properly truncate the thousandths digit. We then define temporary variable $Whole to be just the truncated integer value, we temporarily strip that from $Percent, then we append a dot and the decimals, excluding the thousandths (which we made wrong so we could get the hundredths rounded properly).

Correct usage of bc in a shell script?

I'm simply trying to multiplying some float variables using bc:
#!/bin/bash
a=2.77 | bc
b=2.0 | bc
for cc in $(seq 0. 0.001 0.02)
do
c=${cc} | bc
d=$((a * b * c)) | bc
echo "$d" | bc
done
And this does not give me an output. I know it's a silly one but I've tried a number of combinations of bc (piping it in different places etc.) to no avail.
Any help would be greatly appreciated!
bc is a command-line utility, not some obscure part of shell syntax. The utility reads mathematical expressions from its standard input and prints values to its standard output. Since it is not part of the shell, it has no access to shell variables.
The shell pipe operator (|) connects the standard output of one shell command to the standard input of another shell command. For example, you could send an expression to bc by using the echo utility on the left-hand side of a pipe:
echo 2+2 | bc
This will print 4, since there is no more here than meets the eye.
So I suppose you wanted to do this:
a=2.77
b=2.0
for c in $(seq 0. 0.001 0.02); do
echo "$a * $b * $c" | bc
done
Note: The expansion of the shell variables is happening when the shell processes the argument to echo, as you could verify by leaving off the bc:
a=2.77
b=2.0
for c in $(seq 0. 0.001 0.02); do
echo -n "$a * $b * $c" =
echo "$a * $b * $c" | bc
done
So bc just sees numbers.
If you wanted to save the output of bc in a variable instead of sending it to standard output (i.e. the console), you could do so with normal command substitution syntax:
a=2.77
b=2.0
for c in $(seq 0. 0.001 0.02); do
d=$(echo "$a * $b * $c" | bc)
echo "$d"
done
To multiply two numbers directly, you would do something like:
echo 2.77 * 2.0 | bc
It will produce a result to 2 places - the largest number of places of the factors. To get it to a larger number of places, like 5, would require:
echo "scale = 5; 2.77 * 2.0" | bc
This becomes more important if you're multiplying numerals that each have a large number of decimal places.
As stated in other replies, bc is not a part of bash, but is a command run by bash. So, you're actually sending input directly to the command - which is why you need echo. If you put it in a file (named, say, "a") then you'd run "bc < a". Or, you can put the input directly in the shell script and have a command run the designated segment as its input; like this:
cat <<EOF
Input
EOF
... with qualifiers (e.g. you need to write "" as "\", for instance).
Control flow constructs may be more problematic to run in BC off the command line. I tried the following
echo "scale = 6; a = 2.77; b = 2.0; define f(cc) { auto c, d; c = cc; d = a*b*c; return d; } f(0); f(0.001); f(0.02)" | bc
and got a syntax error (I have a version of GNU-BC installed). On the other hand, it will run fine with C-BC
echo "scale = 6; a = 2.77; b = 2.0; define f(cc) { auto c, d; c = cc; d = a * b * c; return d; } f(0); f(0.001); f(0.02)" | cbc
and give you the expected result - matching the example you cited ... listing numbers to 6 places.
C-BC is here (it's operationally a large superset of GNU-BC and UNIX BC, but not 100% POSIX compliant):
https://github.com/RockBrentwood/CBC
The syntax is closer to C, so you could also write it as
echo "scale = 6, a = 2.77, b = 2.0; define f(cc) { return a * b * cc; } f(0); f(0.001); f(0.02)" | cbc
to get the same result. So, as another example, this
echo "scale = 100; for (x = 0, y = 1; x < 50; y *= ++x); y" | cbc
will give you 50 factorial. However, comma-expressions, like (x = 0, y = 1) are not mandated for bc by POSIX, so it will not run in other bc dialects, like GNU BC.

How to round a floating point number upto 3 digits after decimal point in bash

I am a new bash learner. I want to print the result of an expression given as input having 3 digits after decimal point with rounding if needed.
I can use the following code, but it does not round. Say if I give 5+50*3/20 + (19*2)/7 as input for the following code, the given output is 17.928. Actual result is 17.92857.... So, it is truncating instead of rounding. I want to round it, that means the output should be 17.929. My code:
read a
echo "scale = 3; $a" | bc -l
Equivalent C++ code can be(in main function):
float a = 5+50*3.0/20.0 + (19*2.0)/7.0;
cout<<setprecision(3)<<fixed<<a<<endl;
What about
a=`echo "5+50*3/20 + (19*2)/7" | bc -l`
a_rounded=`printf "%.3f" $a`
echo "a = $a"
echo "a_rounded = $a_rounded"
which outputs
a = 17.92857142857142857142
a_rounded = 17.929
?
You can use awk:
awk 'BEGIN{printf "%.3f\n", (5+50*3/20 + (19*2)/7)}'
17.929
%.3f output format will round up the number to 3 decimal points.
Try using this:
Here bc will provide the bash the functionality of caluculator and -l will read every single one in string and finally we are printing only three decimals at end
read num
echo $num | bc -l | xargs printf "%.3f"

How to use expr on float?

I know it's really stupid question, but I don't know how to do this in bash:
20 / 30 * 100
It should be 66.67 but expr is saying 0, because it doesn't support float.
What command in Linux can replace expr and do this equalation?
bc will do this for you, but the order is important.
> echo "scale = 2; 20 * 100 / 30" | bc
66.66
> echo "scale = 2; 20 / 30 * 100" | bc
66.00
or, for your specific case:
> export ach_gs=2
> export ach_gs_max=3
> x=$(echo "scale = 2; $ach_gs * 100 / $ach_gs_max" | bc)
> echo $x
66.66
Whatever method you choose, this is ripe for inclusion as a function to make your life easier:
#!/bin/bash
function pct () {
echo "scale = $3; $1 * 100 / $2" | bc
}
x=$(pct 2 3 2) ; echo $x # gives 66.66
x=$(pct 1 6 0) ; echo $x # gives 16
just do it in awk
# awk 'BEGIN{print 20 / 30 * 100}'
66.6667
save it to variable
# result=$(awk 'BEGIN{print 20 / 30 * 100}')
# echo $result
66.6667
I generally use perl:
perl -e 'print 10 / 3'
As reported in the bash man page:
The shell allows arithmetic expressions to be evaluated, under certain circumstances...Evaluation is done in fixed-width integers with no check for overflow, though division by 0 is trapped and flagged as an error.
You can multiply by 100 earlier to get a better, partial result:
let j=20*100/30
echo $j
66
Or by a higher multiple of 10, and imagine the decimal place where it belongs:
let j=20*10000/30
echo $j
66666
> echo "20 / 30 * 100" | bc -l
66.66666666666666666600
This is a simplification of the answer by paxdiablo. The -l sets the scale (number of digits after the decimal) to 20. It also loads a math library with trig functions and other things.
Another obvious option:
python -c "print(20 / 30 * 100)"
assuming you are using Python 3. Otherwise, use python3.

Resources