2

How can I use regex, with grep, to print all lines that do not contain a pattern. I cannot use -v because I want to implement the regex within a much more complicated one, for which -v would be impractical.

But whenever I try to print lines that do not contain a pattern, I do not get the expected output.

For example, if I have this file:

blah blah blah
hello world
hello people
something

And I want to print all lines that do not contain hello, the output should be:

blah blah blah
something

I tried something like this, but it won't work:

egrep '[^hello]' file

All answers on SO use -v, I can't find one using regex

buydadip
  • 8,890
  • 22
  • 79
  • 154
  • related http://stackoverflow.com/questions/26804586/grep-to-check-if-a-line-starts-with-a-specific-string . ie, `grep -P '^.*hello(*SKIP)(*F)|^' file` – Avinash Raj Jan 02 '15 at 01:59
  • You can also pipe the output of grep to another grep. There is no need to do everything in one grep. – nhahtdh Jan 02 '15 at 02:26

3 Answers3

5

You cannot use "whole" words inside of a character class. Your regular expression currently matches any character except: h, e, l, o. You could use grep with the following option and implement Negative Lookahead ...

grep -P '^(?!.*hello).*$' file

Ideone Demo

Community
  • 1
  • 1
hwnd
  • 69,796
  • 4
  • 95
  • 132
  • you don't need to add `-o` parameter when you're trying to print the whole line. Just `grep -P '^(?!.*hello)' file` would be fine. This matches the start of a line only it won't contain the word `hello`. `-p` alone helps you to print those matched lines. – Avinash Raj Jan 02 '15 at 02:01
1

I see you asking for regex, and can not use -v. What about some other program like awk,sed?
If not, does your system not have awk, sed etc?

awk '!/hello/' file

sed '/hello/d' file

sed -n '/hello/!p' file
Jotne
  • 40,548
  • 12
  • 51
  • 55
0

This can help you.

grep -E '^[^(hello)]*$' file