Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Negative matching using grep (match lines that do not contain foo)

Tags:

regex

grep

I have been trying to work out the syntax for this command:

grep ! error_log | find /home/foo/public_html/ -mmin -60 

OR:

grep '[^error_log]' | find /home/baumerf/public_html/ -mmin -60 

I need to see all files that have been modified except for those named error_log.

I've read about it here, but only found one not-regex pattern.

like image 732
jerrygarciuh Avatar asked Aug 23 '10 14:08

jerrygarciuh


People also ask

How do you grep for lines that don't match?

To display only the lines that do not match a search pattern, use the -v ( or --invert-match ) option. The -w option tells grep to return only those lines where the specified string is a whole word (enclosed by non-word characters). By default, grep is case-sensitive.

Which of the grep command option will select non matching lines from given file?

-v, --invert-match Invert the sense of matching, to select non-matching lines. -w, --word-regexp Select only those lines containing matches that form whole words.

How do you exclude characters in grep?

To exclude particular words or lines, use the –invert-match option. Use grep -v as a shorter alternative. Exclude multiple words with grep by adding -E and use a pipe (|) to define the specific words.

How to use negative matching in grep?

To use negative matching in grep, you should execute the command with the -v or --invert-match flags. This will print only the lines that don’t match the pattern given.

How can I exclude a file from grep?

In your case, you presumably don't want to use grep, but add instead a negative clause to the find command, e.g. If you want to include wildcards in the name, you'll have to escape them, e.g. to exclude files with suffix .log:

Can I use [^error_log] as a negative pattern?

[^error_log] would never ever work anyway, [] are char classes, regexp 's in general are not good at negative patterns (unless the engine implements negative lookaheads). Also check out the related -L (the complement of -l ).


2 Answers

grep -v is your friend:

grep --help | grep invert   

-v, --invert-match select non-matching lines

Also check out the related -L (the complement of -l).

-L, --files-without-match only print FILE names containing no match

like image 135
Motti Avatar answered Oct 05 '22 08:10

Motti


You can also use awk for these purposes, since it allows you to perform more complex checks in a clearer way:

Lines not containing foo:

awk '!/foo/' 

Lines containing neither foo nor bar:

awk '!/foo/ && !/bar/' 

Lines containing neither foo nor bar which contain either foo2 or bar2:

awk '!/foo/ && !/bar/ && (/foo2/ || /bar2/)' 

And so on.

like image 45
fedorqui 'SO stop harming' Avatar answered Oct 05 '22 08:10

fedorqui 'SO stop harming'