List the files containing a particular word in their text
Solution 1
Use the -l
or --files-with-matches
option which is documented as follows:
Suppress normal output; instead print the name of each input file from which output would normally have been printed. The scanning will stop on the first match. (
-l
is specified by POSIX.)
So, for you example you can use the following:
$ grep check * -lR
Solution 2
find . -type f -exec grep -l check {} +
You probably don't want to use the -R
option which with modern versions of GNU grep
follows symlinks when descending directories. Use the -r
option instead there which since version 2.12 (April 2012) no longer follows symlinks.
If your grep is not the GNU one, or is older than version 2.12, or if you need your code to be portable to non-bleeding-edge-GNU systems, use the find
command above.
Otherwise, you can do:
grep -rl check .
Don't use *
(as that would omit hidden files in the current directory (and in the current directory only) and would cause problems for files whose name starts with a -
), avoid passing options after arguments as that's not guaranteed to work depending on the environment and is not portable.
Solution 3
grep -lR "text-to-find" <where-to-find>
also works fine.
e.g., grep -lR "NAVIGATE" .
where we find the word NAVIGATE
in the .
in the current directory.
Solution 4
Try this:
find . -type f | xargs grep -c check $1 | grep -v ":0"
As for the grep
flags ...
-c
will return a filename followed by : and a number indicating how many times the search string appears in the given file.
-v
will take the output from the first grep
search, filter out the files with zero results, and print out just the files with non-zero results.
Related videos on Youtube
ekoeppen
Updated on September 18, 2022Comments
-
ekoeppen over 1 year
I would like to list the files recursively and uniquely that contain the given word.
Example: Checking for word 'check', I normal do is a grep
$ grep check * -R
But as there are many occurrence of this word, I get a lot of output. So I just need to list the filenames that contain the given search word. I guess some trick with
find
andxargs
would suffice here, but not sure.Any ideas?
-
Kos over 11 yearsWorks on MSYS too. Great!
-
Scott - Слава Україні almost 8 yearsThis will get a false negative if you have file(s) (or director(ies)) whose names contain
:0
. It's better to dogrep -v ':0$'
. Even that will choke on pathnames that contain newline(s). -
Shrout1 over 7 yearsI used
grep -rl "text to find" "/usr/share"
and it worked great! -
kashmoney over 2 yearsIs there a way to do the same thing but skip files above certain size (i.e. not scanning files greater than 50MB)