Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inserting variables within my awk statement

Tags:

bash

awk

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

like image 877
Jim Avatar asked Apr 07 '12 13:04

Jim


Video Answer


2 Answers

You can use -v option:

ZONE=`date "+%Z %Y"`
DAY=`date "+%a"`
awk -vzone="$ZONE" -vday="$DAY" 'BEGIN { print zone, day }'
like image 155
yazu Avatar answered Sep 30 '22 18:09

yazu


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.

like image 41
ctt Avatar answered Sep 30 '22 18:09

ctt