How to print a variable inside awk

I want 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 to get the desired result as follows:

 tau_2.54_even_v1.xls sum/NR 

Can anyone help me with this?

+6
scripting bash awk
source share
4 answers

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 
+8
source share

First, you need export environment variables if you want them to be passed in a child process environment, such as awk .

Secondly, you can use ENVIRON["name"] to get the 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}' 
+14
source share

Remember that you can set "AWK variables" on the command line

 awk -v FOO=bar '...<AWK code that uses the AWK variable FOO>...' 
+10
source share

Ok, I used a mixture of the above solutions and got her working with this

 printf "\n${file}_${f}_${order}_v1.xls " >> Safe/P-state-summary.xls awk '{sum+=$3}; END {print sum/NR}' ${file}_${f}_${order}_v1.xls >> Safe/P-state-summary.xls 
0
source share

All Articles