[英]Bash and awk to do division
I am trying to do a simple division computation between two integers that will result in a float. 我正在尝试在两个整数之间进行简单的除法运算,这将导致浮点数。 I do not want to use bc.
我不想使用BC。 This approach works for me for a different purpose with slightly different syntax but I am not quite sure where I am messing up.
这种方法对我来说使用语法稍有不同的目的可以达到不同的目的,但是我不确定我在哪里弄糟。 I am positive that the variables are getting assigned correctly, but I have an error once I try to do the division, and nothing actually gets assigned to the variable.
我肯定变量已正确分配,但是一旦尝试进行除法,我将遇到错误,并且实际上没有任何内容分配给变量。 Can anyone help?
有人可以帮忙吗?
Thanks in advance! 提前致谢!
rate=`awk '{ shared = "'"${tempRatioArray[0]}"'"; total = "'"${tempRatioArray[1]}"'";\
printf "%3.0f\t", shared/total }' | awk '{print}'`
That is not correct way of using shell variables in awk
and you don't need 2 awk commands. 这不是在
awk
中使用shell变量的正确方法,并且您不需要两个awk命令。
Use it like this: 像这样使用它:
rate=$(awk -v shared="${tempRatioArray[0]}" -v total="${tempRatioArray[1]}" 'BEGIN {
printf "%.3f", (shared/total) }')
You can use bc
: 您可以使用
bc
:
bc -l <<<"scale=3; 5/2"
2.500
Adapting to your code: 适应您的代码:
bc -l <<< "scale=3; ${tempRatioArray[0]} / ${tempRatioArray[1]}"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.