Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm wondering if there is any way to include or exclude files from the results of find(1) based on the output or exit code of another program. Specifically I'd like to be able to run find(1) such that it returns only those files that contain a positive match for a regular expression.

I realize that this can be accomplished by piping the output of find(1) through egrep but I'd like to be able to do it all from within find(1).

For example, is there any way to convert the following into a single invocation of find(1) without any pipes?

find . [test] | xargs egrep -l [regex]
share|improve this question
up vote 2 down vote accepted

-exec evaluates to "true" if the command returns zero (success):

find . -type f -exec egrep -qs "regex" {} \; -print

Replace -print with action of your choice.

However, consider that this way egrep is executed once for each file. Compare:

equal ~/code $ time find -type f -exec grep -qs bin/env {} \; -print | wc -l

real    0m0.760s
user    0m0.104s
sys     0m0.596s


equal ~/code $ time find -type f -print0 | xargs -0 egrep -l bin/env | wc -l

real    0m0.021s
user    0m0.003s
sys     0m0.023s

(Tested on a rather small Git repository, 300 files, ~2.6 MB.)

share|improve this answer

You must log in to answer this question.

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