2

I was trying to create a regex, to be used in a grep statement to match lines that do not contain a word. In the example below I have the words uhu, uhuu, uhuuu, uhuuu one in each line. I used an echo to do that in one command. Results are:

line1 = uh - end
line2 = uhu - end
line3 = uhuu - end
line4 = uhuuu - end
line5 = uhuuuu - end

Never mind the line number and the end word. So, I wanted to grep uhuu's with 2 and 4 repetitions only, that is line 3 and 5. I tried:

echo -e 'line1 = uh - end\nline2 = uhu - end\nline3 = uhuu - end\nline4 = uhuuu - end\nline5 = uhuuuu - end' | grep -E 'uh(u{2}|u{4})'
line3 = uhuu - end
line4 = uhuuu - end
line5 = uhuuuu - end

It brings line 3 and 5, but also line 4 because uhuuu has 2 u's, plus a 3rd one. So my question is, using Regex, is it possible to exclude that 4th line taking into account only the 'uhuuu' word?

I know I could accomplish this with a pipe and grep -v at the end of everything but I was wondering if this could be done using RegEx.

I checked this link but couldn find a way to make it work for my case. Thank you https://stackoverflow.com/questions/406230/regular-expression-to-match-line-that-doesnt-contain-a-word#=

5
  • try egrep -v "uh(u{2}|u{4})" Commented Dec 24, 2016 at 20:36
  • @Devian That suffers from the same problem: uhu{2} matches with at least two trailing us and so will match longer items. Commented Dec 24, 2016 at 21:08
  • it seems like it is, my fault Commented Dec 24, 2016 at 21:11
  • how about using a lookahead something like grep -P 'uh(?:u{2}|u{4})(?!u)' (see demo). Commented Dec 24, 2016 at 21:19
  • Thanks @bobblebubble, this works like a charm, even though I don't understand yet how lookahead (lookaround) works. Commented Dec 24, 2016 at 23:01

1 Answer 1

1

Use a word boundary meta character after grouping:

grep -E 'uh(u{2}|u{4})\b'
Sign up to request clarification or add additional context in comments.

1 Comment

That's right @revo, I had tried it before but had even forgotten. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.