【问题标题】:Showing which files matched a grep that is looking through all files from a collection显示哪些文件与正在查看集合中所有文件的 grep 匹配
【发布时间】:2012-04-12 17:21:33
【问题描述】:

假设我有一个这样的文件集合:

echo -e "apple\n cherry" >> f1.txt; 
echo -e "grape\n strawberry" >> f2.txt; 
echo -e "orange\n cherry" >> f3.txt; 

我想找到每个包含“樱桃”一词的文件。我可以这样做:

ls *.txt | xargs cat | grep cherry

但这只是返回从 f1 和 f3 匹配的两行,而不显示“源”文件,如下所示:

cherry
cherry

我想查看这些匹配项来自的文件——像这样:

f1.txt ->  cherry 
f3.txt ->  cherry

有没有办法简单地从命令行做到这一点?

【问题讨论】:

  • 等等...你在研究你得到的答案吗? :^)
  • 小世界!顺便说一句,你帮助我们的论文被 AAAI 接受了——结果非常好。这是链接:aaai.org/ocs/index.php/WS/AAAIW11/paper/view/3983
  • 哦 - 这不是一项研究 - 我真的需要知道答案。
  • 谢谢,准备把它添加到我的简历中!
  • 没有人再阅读手册页了吗? :) 这些年来,你是如何vi-ing 多个包含匹配项的文件的? vi $(grep -l foo *.txt)。 :)

标签: shell command-line grep


【解决方案1】:
jcomeau@intrepid:/tmp$ echo -e "apple\n cherry" >> f1.txt; 
jcomeau@intrepid:/tmp$ echo -e "grape\n strawberry" >> f2.txt; 
jcomeau@intrepid:/tmp$ echo -e "orange\n cherry" >> f3.txt; 
jcomeau@intrepid:/tmp$ grep cherry *txt
f1.txt: cherry
f3.txt: cherry

【讨论】:

  • JC,你太棒了 - 谢谢。 SO说我需要11分钟的时间来批准答案......
【解决方案2】:

-l 选项意味着 grep 将仅打印匹配的文件名,而不是匹配的行,因此您的任务可以通过以下方式完成:

$ grep -l cherry *.txt
f1.txt
f3.txt

(注意ls 和xargs 对于此任务是不必要的,grep 将除第一个位置参数之外的所有位置参数视为要查看的文件)

【讨论】:

    【解决方案3】:

    尝试grep -H 打印文件名和匹配项。从手册页:

       -H, --with-filename
              Print  the  file  name for each match.  This is the default when
              there is more than one file to search.
    

    我发现这在使用 grep 和 find 时很有用。

    【讨论】:

      【解决方案4】:

      当你做ls *.txt | xargs cat时,你会得到一个合并的数据流,所以文件名信息丢失了,后续grep无法恢复。

      这些应该可以工作:

      ls *.txt | xargs grep cherry
      

      甚至更简单:

      grep cherry *.txt
      

      【讨论】:

        【解决方案5】:

        grep 樱桃 *.txt 这应该为你做它

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-04-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-03-18
          • 2012-08-31
          • 2014-08-23
          相关资源
          最近更新 更多