Comments on: Safely escape variables in awk https://backreference.org/2010/03/13/safely-escape-variables-in-awk/ Proudly uncool and out of fashion Tue, 26 Jan 2016 00:04:04 +0000 hourly 1 https://wordpress.org/?v=5.8.2 By: Steven B. https://backreference.org/2010/03/13/safely-escape-variables-in-awk/#comment-25246 Tue, 26 Jan 2016 00:04:04 +0000 http://backreference.org/?p=1066#comment-25246 Thanks for this. Based on tests with GNU Awk 4.1 this didn't work well for me when passing the regex string to an external program (tre-agrep) which supports regex statements. Here is a similar solution:

#
# Escape regex symbols
#
function regesc(str, safe) {
safe = str
gsub(/[][^$*?+{}\\()|]/, "[&]", safe)
gsub("[\\^]","\\^",safe) # replace "[^]" with "[\^]"
return safe
}

Using square brackets instead of \ to escape, and special case for ^ since it's legitimate inside a square bracket.

]]>