ckp
ckp

Reputation: 11

Variable pattern matching awk

I have an input file "myfile" and a shell variable "VAR" whose contents are shown below:

# cat myfile
Hello World
Hello Universe
# echo $VAR
World

I need to process all lines in "myfile" which contains pattern "World" using awk. It works if i do as shown below:

# awk '/World/ { print $0 }' myfile

But i could not use VAR to do the same operation. I tried the following even knowing that these will not work:

# awk '/$VAR/ { print $0 }' myfile

and

# awk -v lvar=$VAR '/lvar/ { print $0 }' myfile

and

# awk -v lvar=$VAR 'lvar { print $0 }' myfile

Please let me know how to match the contents of VAR in awk.

Thanks in advance

Upvotes: 0

Views: 4462

Answers (3)

Phil A
Phil A

Reputation: 1

If you export your variable, it becomes a simpler solution:

export VAR
awk '$0~ENVIRON["VAR"]' myfile

Takes out any issues of reprocessing the variable's value.

Upvotes: 0

Ed Morton
Ed Morton

Reputation: 204731

This is probably what you want:

awk -v lvar="$VAR" '$0~lvar' myfile

Never do

awk "/$VAR/" myfile

or any other syntax that expands shell variables inline within the awk script such that they become part of the script as it can produce all sorts of bizarre failures and error messages depending on how the shell variable is populated since with that syntax there is no variable inside awk but the shell variable contents are instead integrated into the script as if you'd hard-coded it.

Always do the above using -v or

awk 'BEGIN{lvar=ARGV[1]; delete ARGV[1]} $0~lvar' "$VAR" myfile

depending on your requirements for the shell expanding backslashes. See http://cfajohnson.com/shell/cus-faq-2.html#Q24 for details.

Only do

awk '$0~lvar' lvar="$VAR" myfile

if you are processing multiple files, need to change initial values of the variable between files, and do not have gawk for BEGINFILE or need to populate those values from environment variables.

Note that all of the above do a regexp match on lvar, if you need a string match instead than use awk -v lvar="$VAR" 'index($0,lvar)'.

Upvotes: 1

Josh Jolly
Josh Jolly

Reputation: 11796

You could use:

awk -v lvar="$VAR" '$0~lvar {print}' myfile

Or (works but not recommended):

awk "/$VAR/ {print}" myfile

Upvotes: 1

Related Questions