Bash Scripting – How to Use a Shell Variable in awk

awkbashvariable

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?

Best Answer

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