7

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 ?

Ayman Hourieh
  • 132,184
  • 23
  • 144
  • 116
Sharat Chandra
  • 4,434
  • 7
  • 49
  • 66
  • You already received an answer to this question from **paxdiablo** here: http://stackoverflow.com/questions/1825509/printing-variable-inside-awk/1825622#1825622 - use awk's variable passing feature – Dennis Williamson Dec 01 '09 at 21:48
  • 1
    Duplicate: http://stackoverflow.com/questions/1825509/printing-variable-inside-awk – glenn jackman Dec 01 '09 at 21:48
  • using the -v option : https://stackoverflow.com/questions/19075671/how-do-i-use-shell-variables-in-an-awk-script?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – Mojtaba Pourmirzaei Apr 09 '18 at 05:25

4 Answers4

18

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}'
Matt Ryall
  • 9,977
  • 5
  • 24
  • 20
11

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

awk -v FOO=bar '...<AWK code that uses the AWK variable FOO>...'
TheBonsai
  • 15,513
  • 4
  • 22
  • 14
  • ie: ### date | awk -v USER=$USER '{ print USER ": " $0 }' ### rzr: Sat Nov 30 18:25:24 CET 2013 ### – RzR Nov 30 '13 at 17:24
9

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
DigitalRoss
  • 143,651
  • 25
  • 248
  • 329
0

Well I used a mixture of the above solutions and got it 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
PeeHaa
  • 71,436
  • 58
  • 190
  • 262
Sharat Chandra
  • 4,434
  • 7
  • 49
  • 66