wenzi
wenzi

Reputation: 1263

External variable in awk

I have a script, in which a script snippet is:

x=3
awk '$2=$x{print $1}' infile

The external variable is x,

but it prompts an error in awk

So in this situation, how to make awk run successfully?

Upvotes: 22

Views: 41010

Answers (5)

Zombo
Zombo

Reputation: 1

set -a    
x=3
awk '$2==ENVIRON["x"]{print $1}' infile

Upvotes: 1

Nik O'Lai
Nik O'Lai

Reputation: 3694

GAWK also supports the following syntax:

awk '$2 == x {print $1}' x=3 infile

An interesting usage is:

awk '$2 == x {print $1}' x=3 infile1 x=10 infile2

in this case x will be equal to 3 for infile1 and equal to 10 for infile2

Upvotes: 2

sampson-chen
sampson-chen

Reputation: 47317

You pass an external variable for use in awk with the -v option:

some_variable=3
awk -v x=$some_variable '$2 == x {print $1}' infile

Also note that you need to change your code from $2=$x to $2 == x

  • Use == instead =: the latter is assignment
  • Do not prefix normal variables with $ inside the awk script.

Aside: You need to specify one -v for each variable you want to pass in, e.g:

var1=2
var2=4
awk -v x=$var1 -v y=$var2 '$2 == x {print y " " $1}' infile

Upvotes: 31

twalberg
twalberg

Reputation: 62459

awk has a -v option for this purpose, or as @nevelis mentions, just use double quotes:

awk -v x=3 ' $2==x {print $1} '

Upvotes: 9

nevelis
nevelis

Reputation: 748

Use "" - bash won't substitute single quotes.

Eg:

x=3 awk "\$2=$x{print \$1}" infile

Upvotes: -1

Related Questions