如何仅在关键字grep搜索之后显示文件名?


15

我目前在目录中有n个数据文件,其中每个文件最多具有1行非常长的数据。我的目录结构是

director/
    data1.json
    data2.json
    data3.json

我知道这些文件中至少有一个包含我要查找的关键字,但是由于一行数据太长,因此它覆盖了我的整个终端。仅在执行关键字grep后如何获取文件名?我正在使用的grep命令是:

grep keyword *.json

Answers:


30

-l参数应该执行您想要的操作。

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

7

您可以将xargs与grep的--null或与ack的--print0结合使用。我发现ack速度更快。

grep -lr --null searchterm * | xargs -I {} -0 echo {}

ack -lr --print0 searchterm * | xargs -I {} -0 echo {}

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.