3

I need to insert contents of variable to parameter function gensub in awk, specifically instead of regular expression's parameter.

I have:

gawk '
 BEGIN {
   a = "abc15d56ef";
   b = gensub(/.*([0-9][0-9])d([0-9][0-9]).*/, "\\2 \\1", "g", a);
   print b;
 }'

output

output:56 15

I need it to be in this form, but it doesn't work:

gawk '
 BEGIN {
   a = "abc15d56ef";
   c="/.*([0-9][0-9])d([0-9][0-9]).*/";
   b = gensub(c, "\\2 \\1", "g", a);
   print b;
 }'

output

output:56 15

1 Answer 1

5

Try:

gawk '
 BEGIN {
   a = "abc15d56ef"
   c=".*([0-9][0-9])d([0-9][0-9]).*"
   b = gensub(c, "\\2 \\1", "1", a)
   print b
 }'
56 15

-- edit: Added number in the third field after comment by @luckman212

3
  • In the above form, I get a warning about the 3rd argument to gensub() being blank. It should be either "1" (1st match) or "g" (all): gensub(c, "\\2 \\1", "g", a)
    – luckman212
    Commented Apr 15, 2019 at 18:31
  • @luckman212. What version of gawk are you using, I get no such warning in gawk 4.02. I agree that the man page specifies a number.. Commented Apr 18, 2019 at 8:19
  • v5.0.0 from Homebrew.
    – luckman212
    Commented Apr 18, 2019 at 21:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .