I'm trying to use something like the pattern "John.*Smith" but instead of matching anything in between John and Smith I'd like to match anything between the words as long as it's of X characters length or less.

If X = 5 for instance:

Lines that should be a match:

- John Smith
- Jonh F. Smith

Lines that shouldn't be a match:

- John Ferdinand Smith
- Joe Brown; John Johson; Mary Smith

How could I do that with grep?

2 Answers 2


Try using a "bound".

man regex:

A bound is '{' followed by an unsigned decimal integer, possibly followed by ',' possibly followed by another unsigned decimal integer, always followed by '}'. The integers must lie between 0 and RE_DUP_MAX (255(!)) inclusive, ...

grep -E "John.{0,5}Smith" file
John Smith
John F. Smith

The 0 can be omitted (EDIT: in some implementations):

grep -E "John.{,5}Smith" file
  • {0,5} works!, Omitting the 0, though, fails with "regex parse error". Adding the backslashes like @Frédéric's answer does not give an error but also does not match the desired lines.
    – Thums
    Nov 10, 2021 at 21:01
  • Note that that would also match Johnnie Smith. Or Mark John; Smith L.J.. Something like John [^;]{0,3} Smith might work to avoid that.
    – ilkkachu
    Nov 10, 2021 at 22:35

I would use the following command :

grep 'John.\{,5\}Smith'

. is for any characters.

\{,5\} is for the repetition up to 5 times.

  • .{0,5} is what worked for me. With the backslashes the pattern matches no lines
    – Thums
    Nov 10, 2021 at 21:01
  • I had to insert backslashes to make it works… but I didn’t tried grep -E or egrep. Nov 10, 2021 at 21:07
  • The ,n is for up to 5, which is was in the question. Nov 10, 2021 at 21:23
  • 1
    @Thums, in "basic regexes" or BRE, as used by grep, it's \{n,m\} with backslashes. In "extended regexes" or ERE, as used by grep -E (and awk and closer to what the more modern ones like Perl regexes look like), it's {n,m} without backslashes.
    – ilkkachu
    Nov 10, 2021 at 22:18
  • 1
    Omitting the lower bound (i.e. {,5} and not {0,5}) seems to work in GNU grep and GNU awk, but not in whatever the grep on my Mac is (gives an error), nor in Perl (warns, and matches the characters literally). So yeah, just spell out the 0.
    – ilkkachu
    Nov 10, 2021 at 22:25

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .