How to coerce AWK to evaluate string as math expression?

前端 未结 5 824
一生所求
一生所求 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 07:04

    Here's a simple one liner!

    math(){ awk "BEGIN{printf $1}"; }
    

    Examples of use:

    math 1+1  
    

    Yields "2"

    math 'sqrt(25)'
    

    Yeilds "5"

    x=100; y=5; math "sqrt($x) + $y"
    

    Yeilds "15"

提交回复
热议问题