8

I know I can search for a string with:

grep -n -d recurse 'snoopy' * 

and then it shows every file name and instance that contains that string, like:

file/name.txt:23 some snoopy here file/name2.txt:59 another snoopy there file/name2.txt:343 some more snoopy etc... 

The problem is that with many occurrences, the list is huge. How do I make it show only the actual file names that contain the string, without duplicates and without the occurrence?

Only like:

file/name1.txt file/name52.txt file/name28293.txt 

Thanks a lot for any help :)

1
  • 2
    You use the -l argument. Commented Nov 4, 2014 at 21:07

1 Answer 1

18

The -l flag (or, in both BSD and GNU grep, --files-with-matches) does what you want.

From the POSIX spec:

Write only the names of files containing selected lines to standard output. Pathnames shall be written once per file searched. If the standard input is searched, a pathname of "(standard input)" shall be written, in the POSIX locale. In other locales, "standard input" may be replaced by something more appropriate in those locales.

Both BSD and GNU also explicitly guarantee that this will be more efficient. (Older BSD versions say "… grep will only search a file until a match has been found, making searches potentially less expensive", newer BSD and GNU say "The scanning will stop on the first match".) If you don't know which grep you have and which options it has, just type man grep at the shell and you should get the manpage.

Sign up to request clarification or add additional context in comments.

4 Comments

The -l option was in 7th Edition UNIX too, so it is essentially available everywhere.
@JonathanLeffler: Does the builtin grep in busybox and other similar all-in-one-micro-userlands have -l? I was trying to find docs, but every busybox machine I have has the builtin disabled and /bin/grep or /usr/bin/grep is the GNU version…
Accurate answer: I don't know. However, to claim to be a built-in replacement for grep, it pretty much must support -l. One reason for it being a separate executable is that there is probably too much code in grep. That would be especially true if it contains multiple regex packages (PCRE plus the various other packages that tend to be included).
@JonathanLeffler: Yeah, I don't know, and don't want to search the source to busybox and all of its competitors. (At least busybox does include grep, it just isn't enabled on most machines.) I think leaving it at "this is part of the POSIX requirements" gets the idea across that you should be able to count on it, together with your comment that strongly implies any pre-POSIX system ought to have it as well…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.