15

So I am trying to find 6-letter words that consist of one character repeated three times followed by another character repeated three times. For example aaabbb or oookkk.

I am trying:

grep -E "[a-z]\1{3}\S[a-z]\1{3}" filename

First, is the regex correct? Second why am I getting grep: Invalid back reference?

5
  • 1
    Please explain what exactly you need to match. Your regex is not correct so I can't understand what you are after. Are you looking for words that consist of 3 repetitions of one character and then three repetitions of another? Or do you also want to match aaabbbfoobar? What about aaaabbb? Ideally, show us some example input and your desired output.
    – terdon
    Dec 21, 2014 at 11:13
  • 1
    A backreference should refer to something, and you haven't specified what that something is. Usually you group an expression using parentheses to do so. For example: grep -E '([a-z]{2})([0-9]{2})\2\1' would match aa9999aa.
    – muru
    Dec 21, 2014 at 11:19
  • @terdon Are you looking for words that consist of 3 repetitions of one character and then three repetitions of another? Yes. Or do you also want to match aaabbbfoobar? No. Only words like oookkk (no longer than 6 characters) NOT words containing oookkk like oookkkfoobar Dec 21, 2014 at 11:19
  • @HighlightsFactory OK, in that case use the grep -w example I gave in my answer.
    – terdon
    Dec 21, 2014 at 11:22
  • One more thing, do you also want to match aaaaaa or do you need at least two different characters? Please consider giving us example input and desired output.
    – terdon
    Dec 21, 2014 at 11:27

1 Answer 1

19

No, it's not correct. I have no idea what the \1{3} is supposed to be but that's what is causing you problems. If you want to find lines that contain three repeated characters followed by three other repeated characters, you can use this:

grep -E '([a-z])\1{2}([a-z])\2{2}'

The \1 refers to the first captured group. You can capture groups by using parentheses. Then, \1 is the 1st such group and \2 is the second and so on. Since you had no captured groups, grep was complaining about an invalid reference since it had nothing to refer to. So, in the regex above, the parentheses are capturing the two groups. Then, you want {2} and not {3} since the initial match is also counted.

You don't specify whether you need the match to be a word or whether you also want to match within words. If you want the entire word to match (and exclude things like aaaabbb, use this instead:

grep -wE '([a-z])\1{2}([a-z])\2{2}'

To print only the matched portion of the line (the word) and not the entire line, use (GNU grep only):

grep -owE '([a-z])\1{2}([a-z])\2{2}'

This site is temporarily in read-only mode and not accepting new answers.

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