Home > database >  How to use grep to find all files that contains two specific words?
How to use grep to find all files that contains two specific words?

Time:07-25

I want to find all files that have both patern1 and patern2 words (not those that contain only one of them or none of them).

I used the following but it includes those that also have only one of the two words:

grep -r "patern1|patern2" /path/to/directory

CodePudding user response:

Variant 1:

find . -type f -exec grep -q pattern1 {} \; -a -exec grep -q pattern2 {} \; -a -print

Variant 2:

grep -rlZ pattern1 | xargs -r0 grep -l pattern2

You can combine this sequence for any number of patterns. -Z for grep and -0 for xargs are required to handle names with spaces. If output must be null-terminated, add -Z to last grep too.

CodePudding user response:

Using grep

grep -re 'pattern1.*pattern2' -e 'pattern2.*pattern1' /path/to/directory

CodePudding user response:

I use the follow with

  • ignoring lower uand upper case
  • recursice in folder structure

grep -rnwi . -e "searchstring" | grep -v "exclude string"

  • Related