Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you grep results from 'find'?

Trying to find a word/pattern contained within the resulting file names of the find command.

For instance, I have this command:

find . -name Gruntfile.js that returns several file names.

How do I grep within these for a word pattern?

Was thinking something along the lines of:

find . -name Gruntfile.js | grep -rnw -e 'purifycss'

However, this is doesn't work..

like image 681
reectrix Avatar asked Jun 15 '15 13:06

reectrix


2 Answers

Use the -exec {} + option to pass the list of filenames that are found as arguments to grep:

find -name Gruntfile.js -exec grep -nw 'purifycss' {} +

This is the safest and most efficient approach, as it doesn't break when the path to the file isn't "well-behaved" (e.g. contains a space). Like an approach using xargs, it also minimises the number of calls to grep by passing multiple filenames at once.

I have removed the -e and -r switches, as I don't think that they're useful to you here.


An excerpt from man find:

-exec command {} +
This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files.

like image 103
Tom Fenech Avatar answered Oct 19 '22 23:10

Tom Fenech


While this doesn't strictly answer your question, provided you have globstar turned on (shopt -s globstar), you could filter the results in bash like this:

grep something **/Gruntfile.js

I was using religiously the approach used by Tom Fenech until I switched to zsh, which handles such things much better. Now all I do is:

grep text **/*(.)

which greps text through all regular files in current directory.

I believe this to be much cleaner syntax especially for day-to-day work in shell.

like image 31
rr- Avatar answered Oct 20 '22 00:10

rr-