在Linux中仅列出包含字符串的文件名

7
我希望使用Linux命令列出包含特定字符串的文件名。
使用egrep命令会显示所有包含该字符串的实例,可能会有多个。
例如:
egrep disco music_file*.txt

可能显示;
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?

然而我想要的只是:

music_file1.txt

music_file2.txt

music_file3.txt

问题:在Linux中搜索字符串时,如何只显示每个文件名的一个实例?


这个问题最好在Linux交流平台上讨论,除非你想编写一个能够实现这个功能的程序? - Matt
2个回答

13

在你的 egrep 表达式中添加 -l

egrep -l disco music_file*.txt

来自man grep:

-l,--files-with-matches

抑制正常输出; 相反地,打印每个输入文件的名称,输出通常会被打印。扫描将在第一个匹配项上停止。 (-l由POSIX指定。)


4

grep -l 可以满足你的需求。

  grep -l pattern files*.txt

来自man手册:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接