I have a text file and I am using the grep command with a regular expression to get only the lines which contain three same successive letters, e.g.: aaa bbb ccc ddd

What regular expression do I need to use in : grep "regex" filename

  • 1
    what does grep aaa not get you? Or do you want: grep '\([[:alpha:]]\)\1\1'?
    – mikeserv
    Commented Feb 14, 2015 at 17:47
  • 1
    As mikeserv wrote, or in general grep '\([[:alpha:]]\)\1\{2\}'.
    – jimmij
    Commented Feb 14, 2015 at 17:53
  • did you want to match this aaaa line also? Because this contains three consecutive a's. Commented Feb 15, 2015 at 13:08

2 Answers 2

printf 'aabbbccddd\nabcdef' | grep '\([a-z]\)\1\1'

Output: aabbbccddd

The bracket pair \(\) makes a backreference, which is referenced by \1

  • bracket pair called capturing group used to capture all the characters which are matched by the pattern present inside the capturing group. Here the pattern present inside the capturing group is [a-z]. \1 means we are back-referencing to the group index 1 (ie, we are referring the characters stored inside the group index 1) Commented Feb 15, 2015 at 13:06

using grep

echo -e "aaa bbb ccc ddd\n hello world"|egrep '([a-z])\1{2}'

([a-z]) remembers the first letter found.

\1{2} check to see if the first letter found is repeated two more times.

  • Standard ERE don't support back-references, grep '\([a-z]\)\1\{2\}' (BRE) would be POSIX/portable. Commented Feb 24, 2015 at 22:41
  • I am aware of this..but I believe the newer versions of egrep do support this..for example try echo " heeeloo"|egrep -o --color '([a-z])\1{2}'..this will output the pattern eee,that is, the same output of grep '\([a-z]\)\1\{2\}'
    – repzero
    Commented Feb 25, 2015 at 0:16

You must log in to answer this question.

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