15

I'm trying to print lines that have b not followed by e in a file. I tried using negative look-ahead, but it's not working.

 grep  'b(?!e)' filename
 grep '(?!e)b)' filename
 egrep  'b(?!e)' f3.txt

When I run these commands, nothing shows up, no error or anything else. I checked other people's similar posts as well but was unable to run it.

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
  • 3
    `grep "b[^e]" filename.txt` might do it? Or with `'` on Linux. What if you use `grep -E` for extended regex support? – TessellatingHeckler Apr 22 '16 at 03:44
  • From this thread http://stackoverflow.com/a/9198987 lookarounds are not supported in standard grep, but in GNU grep, `grep -P` might use Perl compatible regexes and support it. – TessellatingHeckler Apr 22 '16 at 03:50

2 Answers2

14

grep -E 'b([^e]|$)' filename

That should match 'b' followed by a character which is not 'e', or 'b' at end-of-line.

pilcrow
  • 56,591
  • 13
  • 94
  • 135
2

If your grep supports Perl regular expressions with -P, look-arounds work:

$ grep -P 'b(?!e)' <<< 'be'     # Gets no output
$ grep -P 'b(?!e)' <<< 'bb'
bb
$ grep -P 'b(?!e)' <<< 'b'
b

The only difference to grep -E (in this case) is that you don't have to take care of the end-of-line situation (see pilcrow's answer).

Community
  • 1
  • 1
Benjamin W.
  • 46,058
  • 19
  • 106
  • 116