Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

awk gsub using variable for pattern matching

Tags:

linux

awk

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.

like image 469
ddjen11 Avatar asked Oct 18 '22 07:10

ddjen11


1 Answers

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)
like image 155
valrog Avatar answered Oct 21 '22 08:10

valrog