awk match shell variable that contains special characters?

How to match a shell variable that contains parenthesis (and other special characters like "!")

file.txt contains:

Charles Dickens
Matthew Lewis (writer)

name="Matthew Lewis (writer)"; 
awk -v na="$name" ' $0 ~ na' file.txt

Ideally this would match $name in file.txt (in this case Matthew Lewis (writer)). But it doesn't work (gives an error) due to the parenthesis in $name. Is it possible to pass a shell variable that contains special characters in Awk's pattern section?

One way:

name='Matthew Lewis \\(writer\\)'
awk -v na="$name" '$0 ~ na {print}' file.txt
Matthew Lewis (writer)

Without modifying the shell variable:

name="Matthew Lewis (writer)"
awk -v na="$name" 'BEGIN {gsub(/\(|\)/,"\\\&", na)} $0 ~ na' file.txt
Matthew Lewis (writer)
1 Like

Hi thanks. This is great:

awk -v na="Matthew Lewis (writer)" 'BEGIN{gsub(/\(|\)/,"\\\\&", na)} $0 ~ na' file.txt

It is actually four \\\\& not three \\\& .. but now it works. Thanks!