5

gsub(pattern, replacement, target): allows a variable to be used for pattern, but does not let me do regular expression.

gsub(/pattern/, replacement, target): lets me do regular expression, but I cannot use a variable for the pattern.

Is there a way to get both variable pattern and regex to work in gsub? I'd like to stick with awk, no sed or shell.

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
ddjen11
  • 51
  • 1
  • 1
  • 4
  • 1
    Seeing the latest answer - do you have an example of what exactly you want to do and how it doesn't work? – Benjamin W. Aug 11 '17 at 21:02
  • thanks, the pattern (re) will be the 2nd parm on the input, used to replace the 1st parm. so looks like: awk 'BEGIN { re = [$2] } { gsub(re, "X", $1); print $1}' <<< '1a2b3c ad' – ddjen11 Aug 16 '17 at 22:03

2 Answers2

2

If you mean something like ruby:

/foo#{pat}bar/

that's not possible in awk (that way). But you can build the pattern when calling gsub.

pat = "[a-z]+"
gsub("foo" pat "bar", rep, target)
valrog
  • 216
  • 1
  • 6
1

You can use a variable containing a regular expression:

$ awk 'BEGIN { re = "[abc]" } { gsub(re, "X"); print }' <<< '1a2b3c'
1X2X3X

But the quoting can get complicated, see Using Dynamic Regexps in the gawk manual.

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116