Thursday, February 19, 2009

Find files that do not contain a pattern - linux

Find files which do not contain a particular pattern or text in one of its lines.

Well, when I first heard of this requirement; I just thought I will use "grep -vl pattern" piped with xargs to a regular find command (i.e. "find . -type f | xargs grep -vl pattern")

Then I realized that "grep -v" only works in line level, i.e. a file which contain the "pattern" in some line(s) may also contain some line(s) which "do not" contain that "pattern"; so as a whole that file will also be in the list of files which "do not" contain the "pattern" even though it contains the pattern.

So the ways would be:

e.g. To find all files which do not contain the pattern "void"

$ find . -type f \! -exec grep -q "void" {} \; -print

From man page of grep command:

-q, --quiet, --silent : Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected.

-l : Suppress normal output; instead print the name of each input file from which output would normally have been printed.

-v : Invert the sense of matching, to select non-matching lines.

One more way would be:

$ find . -type f | while read file
grep "void" $file > /dev/null
[ $? -ne 0 ] && echo $file

Related post:
- Linux find command and logical operations
- Exclude directory from Linux find command

No comments:

© Jadu Saikia