Command Line – How to Grep for Two Patterns in Multiple Files

command linegreptext processing

I have multiple files in multiple directories, and I need a grep command which can return the output only when both the patterns are present in the file. The patterns are like AccessToken and Registrationrequest. The patterns are not in the same line. AccessToken can be in one line and Registrationrequest can be in another line. Also search the same recursively across all files in all directories.


grep -r "string1” /directory/file |  grep "string 2” 
grep -rl 'string 1' | xargs grep 'string2' -l /directory/ file
grep -e string1 -e string2 

Nothing works

Can anyone please help?

Best Answer

Just in case the files are very large and making two passes on them is expensive and you want just the filenames, using find+awk:

find . -type f -exec awk 'FNR == 1 {a=0; r=0} /AccessToken/{a=1} /Registrationrequest/{r=1} a && r {print FILENAME; nextfile}' {} +
  • we set two flag variables a and r for when the corresponding patterns were found, cleared at the start of each file (FNR == 1)
  • when both variables are true, we print the filename and move on to the next file.