I have a text file, test that contains the following string


though in general, X could be any character and M could also be F. I'm trying to select for this string with the following grep command:

grep '\(F\|M\)D.{,5}\(F\|M\)D' test

However, this does not return anything, meaning that the regex cannot select for the string. The \(F\|M\)D part works fine:

➜  ~ grep '\(F\|M\)D' test

Doesn't .{,5} mean up to 5 occurences of any character? What am I missing?

(I'm on mac if that makes a difference)

  • Yes, it makes a difference. Linux has GNU grep, MacOS has BSD grep. There are a number of differences.
    – Barmar
    Nov 12, 2021 at 21:35

2 Answers 2


On a Mac I would try with {0,5} instead of an empty entry ({,5}). Because the empty entry is a GNU extension which may not be supported on the Mac.

Also, just like with the other regex characters, the { and } should be escaped \{0,5\} should work best.

If the 0 is an issue (invalid count), then you can make it with an extra set of parenthesis:


That means those 1 to 5 characters are optional.

  • 1
    ah, the addition of the lower limit turns out to be critical for mac! thanks! Nov 11, 2021 at 19:19

You should be escaping also the brackets:

grep '\(F\|M\)D.\{,5\}\(F\|M\)D' test
  • I get an error that says grep: invalid repetition count(s). Nov 11, 2021 at 19:17
  • Works for me on Ubuntu with echo MDXXXXXMD | grep '\(F\|M\)D.\{,5\}\(F\|M\)D'. What is your operating system?
    – harrymc
    Nov 11, 2021 at 19:18
  • macos. turns out I needed to add a lower limit (see the other answer). Nov 11, 2021 at 19:20

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.