0

How to search multiple strings from multiple files with a single command. May be using grep or find or if there is any other in Linux or Solaris

2 Answers 2

4
find $BASEDIR -type f -exec egrep 'string1|string2|string3' $file /dev/null \;

where $BASEDIR is the root of the search operation. You can also get clever with egrep -R, but I prefer find as I can be more selective about the files by adding -name foo\* , -mtime -100 , or similar qualifiers.

2

MadHatter's solution will certainly work, however, a simpler, imho, command would be to use (e)grep's recursive flag. Such as:

egrep -r 'regex1|regex2' /foo/bar/*

Depending on whether it is more convenient to consider the collection of files in a hierarchy, above, or as a finite set using shell glob'ing as:

egrep 'regex1|regex2' /foo/bar/{file1,file2}
2
  • I forgot to mention, if you have a directory tree with numerous files, or very large files that you know do not contain your string, it may be more efficient to leverage the granularity of find, as MadHatter suggests, or file glob'ing above. For example, egrep 'regex1|regex2' /foo/bar/*/{file1,file2} of course this assumes that you know prior to searching which file(s) may or do contain your search pattern and are simply interested in extracting that data.
    – Tok
    Nov 26, 2010 at 14:11
  • Don't forget you can use multiple globs: grep -E 'regex1|regex2' /foo/bar/*/file[12] /foo/baz/file.[hc] /foo/aaa{bbb,ccc,ddd}eee Nov 26, 2010 at 15:30

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .