nam
nam

Reputation: 3632

Find files that does not contain a string

To find all the files that contain "foo" in current folder, I use:

grep -r "foo" .

To find all the files that contain "bar" in current folder, I use:

grep -r "bar" .

But how to find all files that does not contain 'foo' and 'bar'?

Upvotes: 17

Views: 16226

Answers (6)

vhtc
vhtc

Reputation: 850

In case you need to find files with a specific extension (or name pattern) not containing a string (or pattern):

find . -name "*.ext" | xargs -n1 grep -r -L -P "(foo|bar)"

Upvotes: 0

Owen Lindsell
Owen Lindsell

Reputation: 71

Recursively searches directories for all files that do no contains XYZ

find . -type f | xargs grep -L "XYZ"

Upvotes: 7

Ramadas
Ramadas

Reputation: 510

Try the below. this should work

grep -rL -P "(foo|bar)" .

Upvotes: 2

kofemann
kofemann

Reputation: 4423

Try this one:

  grep  -L -e  "foo\|bar" *

Upvotes: 4

alestanis
alestanis

Reputation: 21863

To print lines that do not contain some string, you use the -v flag:

grep -r -v "bar" . | grep -v "foo"

This gives you all lines that do not contain foo or bar.

To print files that do not contain some string, you use the -L flag. To non-match several strings, you can use regular expressions with the -P flag (there are several regex flags you can use):

grep -r -L -P "(foo|bar)" .

This prints a list of files that don't contain foo or bar.

Thanks to Anton Kovalenko for pointing this out.

Upvotes: 27

Zsolt Botykai
Zsolt Botykai

Reputation: 51603

With awk, something like:

awk 'BEGIN {f=ARGV[1] ; ff=0} f != FILENAME { if ( ff>0 ) { print f } ; ff=0 ; f=FILENAME } /SEARCHSTRING/ {ff=1} END {if ( ff>0 ) { print f } }' INPUT_FILE_LIST(PATTERN)

Basically it reads every input file and if sees your SEARCHSTRING (which can be a regex), it saves that info. After finishing the current file (or after the last file), check if it found something, and if so, print the previous filename.

Upvotes: 2

Related Questions