Sergio Peres
Sergio Peres

Reputation: 55

awk display variable with environment content

I'm getting from system one variable that returns a string, like:

$VARIABLE/dir/text.file

I tryed to use gsub, but I'm missing something:

onstat -c | grep ^MSGPATH | awk 'gsub (/$INFORMIXDIR/, ${INFORMIXDIR}) {print $2}'

It returns error:

awk: cmd. line:1: gsub (/$INFORMIXDIR/, ${INFORMIXDIR}) {print $2}
awk: cmd. line:1:                        ^ syntax error
awk: cmd. line:1: gsub (/$INFORMIXDIR/, ${INFORMIXDIR}) {print $2}
awk: cmd. line:1:                                     ^ 0 is invalid as number of arguments for gsub

What could be the problem?

Upvotes: 0

Views: 86

Answers (1)

glenn jackman
glenn jackman

Reputation: 247042

Because the awk body is in single quotes, you can't expand shell variables. The way to do this safely is to pass the value to awk with the -v option:

... | awk -v dir="$INFORMIXDIR" 'gsub (/\$INFORMIXDIR/, dir) {print $2}'

Note that you have to escape the $ in the regular expression, because it is a special regex character (meaning "end of string")

Upvotes: 2

Related Questions