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

link|improve this question

feedback

2 Answers

up vote 4 down vote accepted
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.

link|improve this answer
feedback

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}
link|improve this answer
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 '10 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 – Dennis Williamson Nov 26 '10 at 15:30
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.