将bash表达式传递给AWK以进行浮点运算 [英] passing bash expression to AWK for floating point arithmetic
问题描述
我试图在bash中执行浮点运算,但是由于不支持浮点运算,因此试图使用AWK获得解决方案.以下是我面临的问题:
I was trying to do floating point arithmetic in bash, but as floats are not supported, was trying to get the solution using AWK. Below is the issue i am facing:
我认为这对我来说很好:
I see this working fine for me:
代码
echo - | awk '{printf("%04.4f \n", (-225.2*7+30*6)/17 + (19^2)/9) }'
输出
-42.0301
-42.0301
但是我的动机是"读取一个表达式"并计算出正确的小数点后4位的值,因此请尝试在下面的代码中输入相同的表达式(-225.2 * 7 + 30 * 6)/17 +(19 ^ 2)/9)及其给出的错误值(我想变量会作为字符串传递给awk):
But my motive is to "read an expression" and compute value correct to 4 decimals, so tried below code inputting same expression (-225.2*7+30*6)/17 + (19^2)/9) and its giving incorrect values(i guess variable is passed as string to awk):
代码
read inpt
echo - | awk -v input=$inpt '{printf("%04.4f \n", input) }'
输出
0.0000
0.0000
注意:在这个示例表达式中,请忽略第二个+左右的空格,我可以使用sed或类似的方法删除空格(使用空格时,从bash传递变量时,awk中会出现语法错误).
Note: Please ignore the space around second + in this example expression, that i can remove using sed or similar methods(with space i get syntactical error in awk while passing variable from bash).
我们非常感谢您的帮助.预先感谢
Any help is highly appreciated. Thanks in advance
PS:在我的情况下,bash版本为"bash-4.2".我猜它的bash版本使我无法使用许多其他选项.
PS: the bash version in my case is "bash-4.2". I guess its the version of bash preventing me using from many other options.
推荐答案
您不能直接使用awk评估变量中的数据.在这种情况下,您需要编写算术计算器或使用预先存在的计算器,例如
You can't evaluate data in a variable in awk out of the box. In this case you need to write an arithmetic evaluator or use a pre-existing one, like https://github.com/radare/radare2-bindings/blob/master/awk/calc.awk . Once you fix that missing parenthesis and quote your expression properly, you can:
$ echo "((-225.2*7+30*6)/17 + (19^2)/9)" | awk -f calc.awk
((-225.2*7+30*6)/17 + (19^2)/9) = -42.0301
这篇关于将bash表达式传递给AWK以进行浮点运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!