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
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

  • 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 Apr 15 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.. – Scrutinizer Apr 18 at 8:19
  • v5.0.0 from Homebrew. – luckman212 Apr 18 at 21:09
  • Thanks @luckman212 – Scrutinizer Apr 20 at 8:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.