How to coerce AWK to evaluate string as math expression?

前端 未结 5 813
一生所求
一生所求 2020-12-17 06:25

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
         


        
5条回答
  •  一向
    一向 (楼主)
    2020-12-17 06:42

    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, like

    [edwbuck@phoenix ~]$ echo "s(0.3)" | bc -l
    .29552020666133957510
    

    Note that this would require sin to be shortened to s as that's the bc sine operation.

提交回复
热议问题