bash - awk printf with variable -


the following expression works expected:

$ awk 'begin {print 4/3}' 1.33333 

however if use variable in place of literal value not print expected:

$ awk -v foo=4/3 'begin {print foo}' 4/3 

how can use use variable awk printf expression?

this workaround:

$ printf 'begin {print %s}' 4/3 | awk -f- 1.33333 

note foo=4/3 sets foo string 4/3. when printed via %f, '4/3' treated 4; when printed %s, printed 4/3. if want evaluate expression, need evaluated inside script.

for example:

awk 'end {printf "%f\n", foonum/fooden }' foonum=4 fooden=3 /dev/null 

note bash not floating point arithmetic. produces 1 output:

awk 'end {printf "%s\n", foo }' foo=$((4/3)) /dev/null 

maybe want use bc:

$ bc -l <<< "4/3" 1.33333333333333333333 $ 

Comments