Is there a way to evaluate a string as a math expression in awk?
balter@spectre3:~$ echo "sin(0.3) 0.3" | awk '{print $1,sin($2)}'
sin(0.3) 0.29552
I would like to know a way to also have the first input evaluated to 0.29552.
Is there a way to evaluate a string as a math expression in awk?
balter@spectre3:~$ echo "sin(0.3) 0.3" | awk '{print $1,sin($2)}'
sin(0.3) 0.29552
I would like to know a way to also have the first input evaluated to 0.29552.
With gawk version 4.1.2 :
It's ok with
tolower(FOO)
too.Here's a simple one liner!
Examples of use:
Yields "2"
Yeilds "5"
Yeilds "15"
You can just create your own eval function which calls awk again to execute whatever command you want it to:
awk lacks an
eval(...)
function. This means that you cannot do string to code translation based on input after the awk program initializes. Ok, perhaps it could be done, but not without writing your own parsing and evaluation engine in awk.I would recommend using
bc
for this effort, likeNote that this would require
sin
to be shortened tos
as that's thebc
sine operation.You can try Perl as it has eval() function.
For the given input,