6

Here is a snippet of my awk statement..I'm trying to insert these 2 variables in the statement but they are not getting evaluated. Can someone point me in the right direction?

ZONE=`date "+%Z %Y"`
DAY=`date "+%a"`

awk '{if (NR<2) {print "["$1, $2, $3"]"}}'

I'm trying this:

awk '{if (NR<2) {print "[" $DAY, $1, $2, $3, $ZONE "]"}}'

This tip here helped solve my problem.

Protect the shell variables from awk by enclosing them with "'" (i.e. double quote - single quote - double quote).

awk '{print "'"$VAR1"'", "'"$VAR2"'"}' input_file

3
  • Where do you want them inserted? What exactly did you try? Commented Apr 7, 2012 at 13:41
  • awk '{if (NR<2) {print "[" $DAY, $1, $2, $3, $ZONE "]"}}' Commented Apr 7, 2012 at 14:08
  • Don't post code in comments, edit your question to add the details. (Did it for you this time.) Commented Apr 7, 2012 at 14:11

3 Answers 3

16

You can use -v option:

ZONE=`date "+%Z %Y"`
DAY=`date "+%a"`
awk -vzone="$ZONE" -vday="$DAY" 'BEGIN { print zone, day }'
Sign up to request clarification or add additional context in comments.

1 Comment

This most often also makes the awk script itself much cleaner than relying on the shell variables being expanded within the script. Also, this will also work in case where the awk script is provided as a separate file (awk -f scripfile.awk).
1

Those variables won't be expanded where they're enclosed in single quotes. Consider using double quotes for your outermost quotes and escaped double quotes inside your awk expression.

I'm only guessing here, though, as you do not appear to have included the actual command you used where your variables have been embedded, but aren't being evaluated.

In the future, or if this answer doesn't help, consider including the command you use as well as its output and an explanation of what you expected to happen. This way, it'll be much easier to figure out what you mean.

Comments

0

I liked yazu's answer above, although to get this to work on my MaxOSX (BSD) environment I had to tweak the syntax:

~ $ ZONE=`date "+%Z %Y"`
~ $ DAY=`date "+%a"`
~ $ awk -v zone="$ZONE" -v day="$DAY" 'BEGIN { print zone, day }'
CEST 2018 Wed

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.