How can I use grep to show just filenames on Linux?


Linux Problem Overview

How can I use grep to show just file-names (no in-line matches) on Linux?

I am usually using something like:

find . -iname "*php" -exec grep -H myString {} \;

How can I just get the file-names (with paths), but without the matches? Do I have to use xargs? I didn't see a way to do this on my grep man page.

Linux Solutions

Solution 1 - Linux

The standard option grep -l (that is a lowercase L) could do this.

From the Unix standard:

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

You also do not need -H in this case.

Solution 2 - Linux

From the grep(1) man page:

> -l, --files-with-matches 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.)

Solution 3 - Linux

For a simple file search, you could use grep's -l and -r options:

grep -rl "mystring"

All the search is done by grep. Of course, if you need to select files on some other parameter, find is the correct solution:

find . -iname "*.php" -execdir grep -l "mystring" {} +

The execdir option builds each grep command per each directory, and concatenates filenames into only one command (+).

Solution 4 - Linux

My command suggestion for getting the filename with path
sudo find /home -name *.php

The output from this command on my Linux OS:

> compose-sample-3/html/mail/contact_me.php


All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncwdView Question on Stackoverflow
Solution 1 - LinuxRandom832View Answer on Stackoverflow
Solution 2 - LinuxIgnacio Vazquez-AbramsView Answer on Stackoverflow
Solution 3 - Linuxuser2350426View Answer on Stackoverflow
Solution 4 - LinuxaplView Answer on Stackoverflow