Ubuntu – Finding the pattern (ab)* using grep

command linegrep

grep ab* filename.txt

The command above finds lines that start with a and end with any number of b's. For example:

a
ab
abb
abb

But how do I fix my command so it finds lines like these?

ab
abab
abababab

I tried grep (ab)* filename.txt, but it won't do it because it's the same as (ab | (ab) | (ab)).

Best Answer

grep (ab)* filename.txt

The one above won't do it because it's the same as (ab | (ab) | (ab)).

No, it won't work because () is special for most shells and you'll get a syntax error:

$ grep (ab)* foo
bash: syntax error near unexpected token `('

Quote your expressions.

Now, grep uses Basic Regular Expressions (BRE) by default. To group part of an expression in BRE, you need to use \(...\):

$ echo xababx | grep -o '\(ab\)*'
abab

Or use Extended Regular Expressions (ERE) or Perl-Compatible Regular Expressions (PCRE), where (...) is enough:

$ echo abab | grep -Eo '(ab)*'
abab
$ echo abab | grep -Po '(ab)*'
abab

See grep manual for BRE vs ERE.

Related Question