Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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 and xargs would suffice here, but not sure.

Any ideas?

share|improve this question

4 Answers 4

up vote 11 down vote accepted

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
share|improve this answer
    
Works on MSYS too. Great! –  Kos Feb 18 '13 at 16:38
find . -type f -exec grep -l check {} +

You probably don't want to use the -R option which follows symlinks when descending directories. Use the -r option instead which since version 2.12 (April 2012) of GNU grep 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 ans that's not guaranteed to work depending on the environment and is not portable.

share|improve this answer

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.

share|improve this answer

grep -rin "whatToFind" locationToFInd

e.g $ grep -rin "vihaan" .

will recursively search and list file names and the corresponding lines which have "vihaan" in them , "." refers to the current directory.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.