【问题标题】:Count multiple occurrences of some text for each file under a directory计算目录下每个文件的某些文本的多次出现
【发布时间】:2016-08-23 23:34:55
【问题描述】:

我正在尝试为目录下的每个文件计算多次出现的某些文本。以下脚本接近我想要的,但它不计算同一行上的多次出现:

grep -rc 'blah' /some/path --include \*.txt

例如给定两个文件:

foo.txt
blah, hey blah
some more text

bar.txt
something blah

上面的脚本产生:

foo.txt:1
bar.txt:1

但我正在寻找的输出是*:

foo.txt:2
bar.txt:1

我知道使用 grep 可以在一个文件中找到总出现次数,然后将结果传递给字数统计:

grep -oh 'blah' foo.txt|wc -l

如何对多个文件执行此操作以实现上述示例*中的输出?

更新

我能想到的最佳解决方案如下:

find /some/path -name '*.txt'|awk '{print "echo -n '\''" 
    $0 "\: '\'' && grep -oh '\''blah'\'' " $0 "|wc -l"}'|bash

【问题讨论】:

    标签: bash grep wc


    【解决方案1】:

    grep -o 在新行上打印每个匹配项 - 然后计数 em up

    dir=$1
    grep -Hor --include '*.txt' 'blah' $dir|
    uniq -c|
    # output after uniq
    #      3 dir/f0.txt:blah
    #      2 dir/f1.txt:blah
    awk '{file=gensub(/^.+\/|:.+/, "", "g", $2); print file ":" $1}'
    

    【讨论】:

      猜你喜欢
      • 2021-05-01
      • 2020-12-07
      • 1970-01-01
      • 1970-01-01
      • 2021-01-11
      • 1970-01-01
      • 1970-01-01
      • 2018-08-25
      • 2014-12-06
      相关资源
      最近更新 更多