back toc next

Passing variables to awk

Let us suppose we have a shell script with a 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 qoutes (').

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

What happens if $SearchString contains a space?

Second Try

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

This solution is OK.