How do I use the regular pattern operator {m,n} in grep?

I have a text file, from which I need to select only those lines, which include the string “tt”. So I tried this on the command line:

grep "t{2}" textfile

Allthough I know the textfile contains words like “rotten” “litter”
the grep command shows no lines, the exit status however is 1.

I tried another regular pattern:

grep "a.*x" textfile

for this one it works.

Asked By: Abdul Al Hazred


You need to escape the braces:

grep 't{2}' textfile

Otherwise { and } are treated as literal characters.

Answered By: jimmij

You need to use the -E (--extended-regexp) or -P (--perl-regexp) option (with GNU grep).

According to the GNU grep(1) man page about Basic vs Extended Regular Expressions, i.e. if you choose not to use these options:

In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions ?, +, {, |, (, and ).

Answered By: vinc17

By default, grep uses Basic Regular Expressions, you need to escape the braces to make grep match multiple characters:

grep 't{2}' textfile

Alternatively, you can use the -E option (or -P option for GNU grep, which uses Perl Compatible Regular Expressions) making grep use Extended Regular Expressions, which can use braces without escaping them:

grep -E 't{2}'
Answered By: cuonglm