grep to match two occurrences of the same pattern with a certain number of characters in between

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

MDXXXXXMD

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
MDXXXXXMD

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

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

1

2 Answers

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:

\(.\{1,5\}\)\?

That means those 1 to 5 characters are optional.

1

You should be escaping also the brackets:

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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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

You Might Also Like