Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print variable inside awk

I want the awk to interpret the variable as follows

#!/bin/bash

file=tau
f=2.54
order=even

awk '{sum+=$2}; END {print '${file}_${f}_${order}_v1.xls', sum/NR}'
${file}_${f}_${order}_v1.xls >> safe/P-state-summary.xls

I want the desired output as follows -

tau_2.54_even_v1.xls   sum/NR

Can anybody help me out with this ?

like image 207
Sharat Chandra Avatar asked Dec 01 '09 21:12

Sharat Chandra


3 Answers

First, you need to export environment variables if you want them to be passed in the environment of a child process like awk.

Second, you can use ENVIRON["name"] to get an environment variable in awk. So the following works for me:

#!/bin/bash

export file=tau
export f=2.54
export order=even

awk '{sum+=$2}; END {print ENVIRON["file"] "_" ENVIRON["f"] "_" ENVIRON["order"] "_v1.xls", sum/NR}'
like image 119
Matt Ryall Avatar answered Oct 03 '22 21:10

Matt Ryall


Don't forget that you can set "AWK variables" on commandline

awk -v FOO=bar '...<AWK code that uses the AWK variable FOO>...'
like image 22
TheBonsai Avatar answered Oct 03 '22 23:10

TheBonsai


I think this is what you want:

#!/bin/bash

file=tau
f=2.54
order=even

awk "{sum+=\$2}; END {print \"${file}_${f}_${order}_v1.xls\", sum/NR}" \
  ${file}_${f}_${order}_v1.xls >> safe/P-state-summary.xls
like image 37
DigitalRoss Avatar answered Oct 03 '22 23:10

DigitalRoss