如何使用find命令查找文本和文件的总出现次数

时间:2012-05-04 02:46:48

标签: unix find

我正在尝试运行find命令来查找特定文本的总出现次数,并使用另一个find命令来获取具有此文本的文件数。

我现在拥有的是这个命令。

find . -name "*.txt" | xargs grep -i "abc"

这会带来所有包含文本abc等的文件。我想获得一个或两个find命令来获取

  1. abc出现的总次数
  2. 包含abc的文件总数。

1 个答案:

答案 0 :(得分:2)

您需要使用更多grep(1)选项来执行您希望的操作:

  1. 对于abc出现的总次数,您需要处理abc在一行上两次或多次的情况:

    find . -name '*.txt' -print0 | xargs -0 grep -o -i abc | wc -l
    
  2. 对于包含abc的文件总数,您需要处理单个文件包含abc两次或更多次的情况:

    find . -name '*.txt' -print0 | xargs -0 grep -l -i abc | wc -l
    
  3. 来自grep(1)联机帮助页:

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

       -o, --only-matching
              Print only the matched (non-empty) parts of a matching
              line, with each such part on a separate output line.
    
相关问题