My goal is to divide 2 text files, each containing a single integer, but limiting the answer to 2 decimal places.
I managed to do it with paste total.txt count.txt | awk '{printf "%.2f\n", $1/$2}'
But I saw another way of using echo 'scale=2; <calculation here>' | bc -l
I couldn't figure out how to pass the numbers from the previous pipe to echo
as an variable/argument, I tried use xargs
but didn't know how to reference it.
I tried this: paste -d/ total.txt count.txt | bc -l | xargs echo 'scale=2;' | bc -l
and this: echo 'scale=2; $(paste -d/ total.txt count.txt)/1' | bc -l
My goal is to pipe output into echo
as a variable for calculation or use commands inside echo
, thank you.
What I would do:
total.txt = 100
count.txt = 3
bc <<< "scale=2; $(paste -d '/' total.txt count.txt);"
33.33
or
echo "scale=2; $(paste -d '/' total.txt count.txt);" | bc -l
33.33
Your attempt:
echo 'scale=2; $(paste -d/ total.txt count.txt)/1' | bc -l
was close, but with single quotes, you prevent the shell to expand the $(command substitution)
.
Learn how to quote properly in shell, it's very important :
"Double quote" every literal that contains spaces/metacharacters and every expansion:
"$var"
,"$(command "$var")"
,"${array[@]}"
,"a & b"
. Use'single quotes'
for code or literal$'s: 'Costs $5 US'
,ssh host 'echo "$HOSTNAME"'
. See
http://mywiki.wooledge.org/Quotes
http://mywiki.wooledge.org/Arguments
https://web.archive.org/web/20230224010517/https://wiki.bash-hackers.org/syntax/words
when-is-double-quoting-necessary