Jim
Jim

Reputation: 161

inserting variables within my awk statement

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

Upvotes: 6

Views: 9617

Answers (3)

Dave Pitts
Dave Pitts

Reputation: 23

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

Upvotes: 0

yazu
yazu

Reputation: 4660

You can use -v option:

ZONE=`date "+%Z %Y"`
DAY=`date "+%a"`
awk -vzone="$ZONE" -vday="$DAY" 'BEGIN { print zone, day }'

Upvotes: 16

ctt
ctt

Reputation: 1435

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.

Upvotes: 1

Related Questions