Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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
add comment

1 Answer

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
60

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

vs.

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

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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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