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 中搜索字符串时,如何只显示每个文件名的一个实例?

4

2 回答 2

11

添加-l到您的 egrep 表达式:

egrep -l disco music_file*.txt

来自man grep

-l, --files-with-matches

抑制正常输出;而是打印通常会从中打印输出的每个输入文件的名称。扫描将在第一次匹配时停止。(-l 由 POSIX 指定。)

于 2013-09-09T09:11:04.130 回答
3

grep -l 应该适合你。

  grep -l pattern files*.txt

从手册页:

      -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.)
于 2013-09-09T09:12:27.673 回答