Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List just the names of files that contain a string in Linux

Tags:

linux

I want to list just the names of files that contain a string using Linux commands.

When using egrep, all the instances of the string are shown, which could be multiples times.

For example:

egrep disco music_file*.txt

Might show;

music_file1.txt: blah blah blah disco stuff

music_file1.txt: disco blah blah blah

music_file1.txt: I like to listen to italodisco

music_file2.txt: I like to party to disco

music_file3.txt: Does your dog like disco?

Whereas all I want is :

music_file1.txt

music_file2.txt

music_file3.txt

Question: How can I just show one instance of each file name when searching for a string in Linux?

like image 252
blarg Avatar asked Sep 09 '13 09:09

blarg


2 Answers

Add -l to your egrep expression:

egrep -l disco music_file*.txt

From man grep:

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

like image 144
fedorqui 'SO stop harming' Avatar answered Nov 16 '22 12:11

fedorqui 'SO stop harming'


grep -l should work for you.

  grep -l pattern files*.txt

From 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.)
like image 43
mawia Avatar answered Nov 16 '22 11:11

mawia