Bhavuk Mathur
Bhavuk Mathur

Reputation: 1078

grep Command for Files with "String1" AND NOT "String2"

I went through the answers on -

  1. Grep regex NOT containing string

  2. http://www.thegeekstuff.com/2011/10/grep-or-and-not-operators/

but I'm still facing some issues to find all the files in a directory which contains "String1" but not "String2".

I tried the following command, but along with the correct result, it also returns the files containing both the strings -

grep -Hrn "String1" . | grep -v -Hrn "String2" 

Kindly correct my mistake.

Upvotes: 2

Views: 1088

Answers (2)

Maroun
Maroun

Reputation: 95978

You can use the -L flag:

-L, --files-without-match  print only names of FILEs containing no match

First you find the files that doesn't contain "String2", then you run on those and find the ones that does contain "String1":

$ grep -L "String2" * | xargs grep -nH "String1"

Upvotes: 3

tripleee
tripleee

Reputation: 189618

This is easy with Awk.

awk 'FNR==1 { if (NR>1 && one && !other) print prev; one=other=0; prev=FILENAME }
    /string1/ { one=1 }
    /string2/ { other=1 }
    END { if (one && !other) print prev }' list of files

Upvotes: 1

Related Questions