Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Here is my script (to find the files that contain a specified pattern) :

find . -type f -exec awk -v vawk="$1" '/'"$vawk"'/ {c++} c>0 {print ARGV[1] ; exit 0 } END { if (! c) {exit 1}}' \{\} \;

I would like to use my script with an argument :

MyScript.sh pattern

My problem is that I don't manage to put the $1 variable in awk.

When I try to debug my script

bash -x MyScript.sh pattern

Here is the output :

+ find . -type f -exec awk -v vawk=pattern '// {c++} c>0 {print ARGV[1] ; exit 0 } END { if (! c) {exit 1}}' '{}' ';'

The $vawk variable seems to be empty.

Any idea ?

share|improve this question
up vote 6 down vote accepted

You seem to be confusing awk variables and shell variables. awk -v vawk="$1" creates an awk variable called vawk, yet you are trying to use shell syntax ($vawk). This doesn't work because the shell doesn't have a variable called vawk. I think what you want is

awk -v vawk="$1" '$0 ~ vawk { c++ } # ...'
#                      ^ awk variable syntax
share|improve this answer
Awesome !!! Thanks for your quick answer – Nicolas Oct 5 '12 at 20:31

Reproduced from this now closed as duplicate question as it includes warnings on the limitations of awk variable passing which one might find useful.

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 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
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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