How do I pass a list of files to grep

I am making use of find and also obtaining a checklist of files I intend to grep via. Just how do I pipe that checklist to grep?

128
2022-06-04 02:21:47
Source Share
Answers: 2

Some variations of grep (as an example on non - ingrained Linux or BSD or Mac OS X) have a -r alternative to make a recursive search. On OpenBSD, make use of -R (and also there is no --exclude as in the instance listed below). This covers straightforward mixes of find with grep.

If your execution does not have the -R flag, or if you desire fancier documents matching standards, you can make use of the -exec primary of find to make it execute grep. A couple of older find executions do not sustain -exec + ; on these systems, make use of a ; as opposed to the + (this will certainly call grep as soon as per documents, so it'll be slower, yet or else the outcome will certainly coincide). Keep in mind the /dev/null method to create grep to show the documents name also if it takes place to be gotten in touch with a file (GNU grep and also FreeBSD/NetBSD/OSX grep have a -H alternative to attain the very same result).

find . -type f -name '*.o' -prune -o -exec grep 'needle' /dev/null {} +
grep -r --exclude='*.o' 'needle' .
10
2022-06-04 19:49:48
Source

Well, the common instance that collaborates with any kind of command that contacts stdout is to make use of xargs, which will certainly allow you attach any kind of variety of command - line debates throughout of a command :

$ find … | xargs grep 'search'

Or to install the command in your grep line with backticks or $(), which will certainly run the command and also replace its result :

$ grep 'search' $(find …)

Note that these commands do not function if the documents names have whitespace, or particular various other "weird characters" (\'" for xargs, \[*? for $(find …)).


Nonetheless, in the details instance of find the capacity to execute a program on the offered debates is constructed - in :

$ find … -exec grep 'search' {} \;

Everything in between -exec and also ; is the command to execute ; {} is changed with the filename located by find. That will certainly execute a different grep for each and every documents ; given that grep can take several filenames and also look them all, you can transform the ; to + to inform find to pass all the matching filenames to grep simultaneously :

$ find … -exec grep 'search' {} \+
168
2022-06-04 19:48:06
Source