A lot of documentation I've read says that the following command should match lines where x appears at least 3 times in a row but no more than 4 times in a row:

grep -E {x}\{3,4}

E.g. http://www.delorie.com/gnu/docs/grep/grep_7.html or http://www.google.com/support/enterprise/static/postini/docs/admin/en/admin_ee_cu/cm_regex.html

Presumably, that means this should return no matches:


But I created a testfile with exactly that and running this command

grep -o -E [x]\{3,4} testfile

returned this output:


It's matching both lines. What's going on? This is in the bash shell on Solaris.

  • 1
    It is true that [x]\{3,4} matches only three or four x but that regex says nothing about what precedes or follows those matching characters. – John1024 Sep 12 '15 at 0:59

First, you should always quote the grep expression, as trying to remember what shell does what with what special character is a pain:

grep -o -E '[x]{3,4}' testfile

Secondly, grep will find a minimal match, it's easy like that, so will happily match a 3 or 4 run of x in a longer run of xs. To prevent this, some sort of boundary condition will be necessary to not match a subset of a longer run. A grep with PCRE support can use zero-width lookarounds to achieve this:

(echo xxx; echo xxxxxx) | grep -P '(?<!x)xxx(?!x)'
  • Got it. I thought specifying the 3 or 4 run was enough of a boundary condition. What's the point of specifying the upper bound or 4 if it basically just ignores that? The documentation I linked seemed to imply {n,m} matches no more than {m} in a row. But that seems to mean that "xxxxx...x" where n(x's) > m will return m x's. Heh. – Fasil Alemante Sep 12 '15 at 1:23
  • @FasilAlemante it does, it matches no more than m, but once it has matched, it does not check the rest of the line. However, consider grep -E 'ax{3,4}b. That will match axxxb and axxxxb but not axxxxxb. – terdon Sep 12 '15 at 10:15

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.