Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to use a variable in regex brace
but it seems does not work.

$ echo 'abcabcabc' | awk  '{ sub(/(abc){2}/,"XXX");  print }'
XXXabc

# this is not a correct result.
$ echo 'abcabcabc' | awk  '{ i=2; sub(/(abc){i}/,"XXX");  print }'
abcabcabc

$ echo 'abcabcabc' | awk  '{ if (/(abc){3}/)  print "ok" }'
ok

# this does not work correctly.
$ echo 'abcabcabc' | awk  '{ i=3; if (/(abc){i}/)  print "ok" }'
share|improve this question
up vote 5 down vote accepted

/.../ only supports Regex constants. To pass a variable, you need to use quotes:

% echo 'abcabcabc' | awk  '{ i=2; sub("(abc){"i"}","XXX");  print }'
XXXabc
  • The Regex pattern before the variable is enclosed in quotes, "(abc){"i

  • Then the variable i is used

  • The pattern after the variable is again enclosed in quotes

share|improve this answer
    
Thanks heemayl. but there is no way with "/ /" ? do i have to use sub function ? how could i solve second example ? – mug896 18 hours ago
    
@mug896 Check my edits. /.../ only supports Regex constants. – heemayl 18 hours ago
    
my second example does not work with quotes – mug896 18 hours ago
1  
@mug896 Use $0 ~ to match the record with the Regex pattern follows. Here: echo 'abcabcabc' | awk '{ i=3; if ($0 ~ "(abc){"i"}") print "ok" }' – heemayl 18 hours ago
1  
To pass a variable, you need to use quotes - That's a GNU awk extension. mawk and BSD awk don't support it. – Sato Katsura 14 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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