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 oneforkper file match.xargsis a better choice here. So I would do something like this:The last one should be OK, at least with GNU find.
The
-print0and-0ensure 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.