Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unix command line ...how to grep and show only file names that contain a string?

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 :)

like image 673
user1227914 Avatar asked Nov 04 '14 21:11

user1227914


People also ask

How do I only grep for filenames?

In order to get only filenames, we can enable the -l or the --files-with-matches flag.

How do I find all files containing specific text on Unix?

You need to use the grep command. The grep command or egrep command searches the given input FILEs for lines containing a match or a text string.

How do I search for a file name in a string?

You can use “grep” command to search string in files. Alternatively, You can also also use the "find " command to display files with specific string. Hope this answer help you.


1 Answers

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.

like image 182
abarnert Avatar answered Nov 16 '22 19:11

abarnert