Possible Duplicate:
Use a script parameter in awk

I have a script, in which a script snippet is

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?


marked as duplicate by jw013, jasonwryan, Renan, Chris Down, Gilles Nov 19 '12 at 23:07

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


A shell variable is just that: a shell variable. If you want to turn it into a awk variable, you need a syntax such as:

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


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

However, those suffer from a problem: escape sequences are expanded in them.

So, for instance if the shell variable contains the two characters backslash and n, the awk variable will end up containing the newline character.

Another approach (but which requires a POSIX awk or nawk (as opposed to the original awk as still found on a few odd Unices)) is to use environment variables:

x="$x" awk '$2 == ENVIRON["x"] {print $1}' infile

Another approach (still with newer awks) is to use the ARGV array in awk:

awk 'BEGIN {x = ARGV[1]; delete ARGV[1]}
  $2 == x {print $1}' "$x" infile
  • As far as I know, ARGV is actually a POSIX feature, it's just defined differently in gawk. – Chris Down Nov 19 '12 at 20:05
  • @ChrisDown Yes, both ARGV and ENVIRON are POSIX but not in the original awk, sorry if I wasn't clear about that. How is it different in gawk? – Stéphane Chazelas Nov 19 '12 at 20:13
  • gawk includes unrecognised options into ARGV, whereas POSIX awk doesn't. – Chris Down Nov 19 '12 at 20:24
  • @ChrisDown, I think you're referring to the case where awk is called with -f as in awk -f script.awk arg1 arg2... where GNU awk doesn't need a -- to mark the end of options if arg1 starts with a - but is not a valid option in that particular version of awk. But that's not relevant to this matter, and I would definitely not rely on that behavior (I would include the -- nevertheless). – Stéphane Chazelas Nov 19 '12 at 20:41

You can't use external variables in awk directly, you have to import them as awk variables first.

awk -v foo="$x" '$2=foo{print $1}' infile

Not the answer you're looking for? Browse other questions tagged or ask your own question.