Does awk support en eval like construct to run a command by concatenating arguments

91 Views Asked by At

This came up in one my recent answers to achieve an use-case of doing a simple arithmetic evaluation using awk alone. Imagine a simple trivial function for this

awkf () { awk -v argv="$*" 'BEGIN{ pi=3.14159265359; printf "%5.5f\n", argv }' ; }

apparently I intended to use it do arithmetic like

awkf "1+2"

but these don't produce the output as expected. I ended up using $* inside double-quotes of the body of the awk to implement this. Though it could work, I don't want to do that. Is there a way to do this to achieve a result as

awkf () { awk -v argv="$*" 'BEGIN{ pi=3.14159265359; printf "%5.5f\n", 1+2}' ; }
#                                                                      ^^^^ when I pass "1+2"

i.e doing awkf "1+2" I'd expect to get result as 3.00000

Suggesting other tools like bc is beyond the scope of this current question. Just wanted to know, how to use awk for this.

1

There are 1 best solutions below

1
karakfa On BEST ANSWER

you can write your script as a function

$ function awkf() { awk "BEGIN{print $*}"; }
$ awkf 4/3
1.33333

$ awkf 3 + 4
7

to add formatting, you have to do quote dance...

$ function awkf() { awk "BEGIN{printf "\"%5.5f\\n\"," $*}"; }