1

I'm trying to find all files that contain 2 specific strings. It needs to match both string1 AND string2. What I've tried so far:

find ~ -type f -name "*.txt" -exec grep -lie 'string1' -lie 'string2' {} \; 

But this seems to find string1 OR string2. How can I find all files containing both string1 AND string2?

In this specific case, I'm trying to find all documents that contain both strings 'sed' and 'lynx'

find ~ -type f -name "*.txt" -exec grep -lie 'sed' -lie 'lynx' {} \; 
3
  • Are they on same line? Commented Jan 9, 2017 at 11:14
  • More than likely they are not on the same line but it is possible in some cases. Commented Jan 9, 2017 at 11:16
  • A minimal input and output with all the cases you want to cover would be useful. Commented Jan 9, 2017 at 11:20

2 Answers 2

2

This will do, even when the strings are not on the same line:

find ~ -type f -name \*.txt -exec grep -iq string1 \{\} \; -exec grep -iq string2 \{\} \; -print

Sign up to request clarification or add additional context in comments.

Comments

1

Use grep as below to match both the patterns.

find ~ -type f -name "*.txt" -exec grep -iE 'string1.*string2|string2.*string1' {} + 

Notice the {} + to apply the grep comamnd on all the files in one-shot, rather than invoking multiple processes.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.