Find all files matching 'name' on linux system, and search with them for 'text'
Solution 1
find / -type f -name filename.ext -exec grep -l 'lookingfor' {} +
Using a +
to terminate the command is more efficient than \;
because find
sends a whole batch of files to grep
instead of sending them one by one. This avoids a fork/exec for each single file which is found.
A while ago I did some testing to compare the performance of xargs
vs {} +
vs {} \;
and I found that {} +
was faster. Here are some of my results:
time find . -name "*20090430*" -exec touch {} +
real 0m31.98s
user 0m0.06s
sys 0m0.49s
time find . -name "*20090430*" | xargs touch
real 1m8.81s
user 0m0.13s
sys 0m1.07s
time find . -name "*20090430*" -exec touch {} \;
real 1m42.53s
user 0m0.17s
sys 0m2.42s
Solution 2
Go to respective directory and type the following command.
find . -name "*.ext" | xargs grep 'lookingfor'
Solution 3
A more simple one would be,
find / -type f -name filename.ext -print0 | xargs -0 grep 'lookingfor'
-print0 to find & 0 to xargs would mitigate the issue of large number of files in a single directory.
Solution 4
I find the following command the simplest way:
grep -R --include="filename.ext" lookingfor
or add -i
to search case insensitive:
grep -i -R --include="filename.ext" lookingfor
Solution 5
Try:
find / -type f -name filename.ext -exec grep -H -n 'lookingfor' {} \;
find
searches recursively starting from the root /
for files named filename.ext
and for every found occurrence it runs grep on the file name searching for lookingfor
and if found prints the line number (-n
) and the file name (-H
).
siliconpi
Updated on December 16, 2020Comments
-
siliconpi over 3 years
I need to find all instances of 'filename.ext' on a linux system and see which ones contain the text 'lookingfor'.
Is there a set of linux command line operations that would work?
-
Didier Trosset over 13 yearsGiven the huge number of files, it is much more efficient to use
xargs
that will startgrep
only once, as in digen's answer. -
Didier Trosset over 13 years
-print0
and-0
has nothing to do with the large number of files. It ensures thatfind | xargs
works when some file have space characters in their names. -
digen over 13 yearsDidier you're absolutely right in this,here is the excerpt from the man page for everyone else, -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by pro‐ grams that process the find output. This option corresponds to the -0 option of xargs.
-
Alexandre about 11 yearsI'd only add the
--color
togrep
, I believe it is a lot easier to see things. Actually, I just realized it doesn't take the alias I defined in.bashrc
.