awk: Force "escaped" representation of a field

Is there any way to get the escaped version of a field in awk? For those that don't understand the question, here is a clarifying example. Lets say a field $1 gives me the string "(dumb'" (I've changed the delimiter to be something other than whitespace). If i use that value in a command in awk as follows... awk{system("echo " $1)}' I get an error Because of the parenthesis and the apostrophe. What I want is to get an escaped version of $1 (which would be \(dumb\' in this case). Is this possible?

Try to use this awk function (I've found it here: Safely escape variables in awk \1)

function escape_pattern(pat,   safe) {
  safe = pat
  gsub(/[][^$.*?+{}\\()|]/, "\\\\&", safe)
  return safe
}
1 Like

Thanks; I had to modify it a bit to get it to do exactly what i wanted, but it worked out.