سؤال

I'm using executing this bash commands inside a search script I've built with php:

find myFolder -type f -exec grep -r KEYWORD {} + 

find myFolder -type f -exec grep -r KEYWORD {} + | wc -l

find myFolder -type f | wc -l

The first line gives me back the filenames where KEYWORD was found.

The second line gives me the number of occurrences and the third line the total number of files.

Is there a way to do this more elegantly and faster?

هل كانت مفيدة؟

المحلول

You can get more efficiency if you avoid -exec, which makes one fork per file match. xargs is a better choice here. So I would do something like this:

find myFolder -type f -print0 | xargs -0 grep KEYWORD

find myFolder -type f -print0 | xargs -0 grep KEYWORD | wc -l

The last one should be OK, at least with GNU find.

The -print0 and -0 ensure that filenames with spaces in them are handled correctly.

Note that grep -r` implies recursive grepping, but as you're only supplying one filename in each invocation it is redundant.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top