18

I use the following command to find files with a given string:

find /var/www/http -type f | xargs grep -iR "STRING1"

But how can I find files which include "STRING1" OR "STRING2" OR "STRING3"?

This code doesn't work:

find /var/www/http -type f | xargs grep -iR "STRING1" | xargs grep -iR "STRING2"
SPnova
  • 353

3 Answers3

25

POSIXly, using grep with -E option:

find /var/www/http -type f -exec grep -iE 'STRING1|STRING2' /dev/null {} +

Or -e:

find /var/www/http -type f -exec grep -i -e 'STRING' -e 'STRING2' /dev/null {} +

With some implementations, at least on GNU systems, OSX and FreeBSD, you can escape |:

find /var/www/http -type f -exec grep -i 'STRING1\|STRING2' /dev/null {} +
cuonglm
  • 153,898
  • @StéphaneChazelas: I edited with the portable one first, would you mind removing the comment so readers won't be confused. – cuonglm Jul 13 '16 at 03:10
8

For ease of maintenance (if your list of strings to search may change in the future), I would put the patterns in a file (eg. patterns.txt) and use the -f switch (-R is unnecessary if you are restricting find to files; -H will give you the file name in case there is only one; -F causes grep to treat the patterns you are searching for as strings, and not regular expressions, which is usually what you want):

find /var/www/http -type f -exec grep -iHFf patterns.txt {} +
Paulo Almeida
  • 746
  • 3
  • 4
  • 1
    just complementing, the strings in the text file patter will be separated by the newline chracter – Thomas Nov 12 '14 at 12:38
7

What's wrong with just using egrep?

egrep -r 'string1|string2|string3' /var/www/http
user1293137
  • 1,732
  • 11
    You should use grep -E .... According to the (e)grep man page direct invocation of egrep is deprecated and the command is only provided to allow historical applications that rely on them to run unmodified. – Anthon Aug 07 '13 at 11:13
  • 1
    Also note that -r is not found on every implementations of the (non-standard) egrep command. – Stéphane Chazelas Aug 07 '13 at 11:26