back toc next

Passing variables to awk

Let us suppose we have a shell variable $SearchString, and we want to pass it to an awk-program (which emulates grep)

First Try

awk '/$SearchString/{ print }' textfile.txt

This doesn't work, because the shell inhibits variable expansion between single quotes (').

awk /$SearchString'/{ print }' textfile.txt

What happens if $SearchString contains a space?

Second Try

awk /"$SearchString"'/{ print }'

Another solution

awk -v ss="$SearchString" '$0 ~ ss { print }'

The -v option is available with POSIX compliant awk implementations. mawk and gawk support it, but oawk does not. Some of the nawk impementations support it, some do not.