查找多个文件中字符串的出现次数

时间:2016-02-01 09:04:06

标签: linux unix sed grep

我想计算一个特定字符串的出现次数。我使用以下命令。字符串可能在同一行中多次出现。有人可以帮我这个。

我正在使用以下命令

sed 's/STRING/STRING\n/g' filename | grep -c "STRING"

我得到以下输出 输出

100

预期输出:

filename 100

也有人可以帮助我如何在文件夹中的多个文件中运行代码并获得类似于下面的输出

输出

filename 100

filename2 300

filename3 200

2 个答案:

答案 0 :(得分:1)

Perl救援:

perl -lne '$c++ while /STRING/g; print(0+$c, " $ARGV"), $c=0 if eof' *

答案 1 :(得分:0)

使用shell加grepwc,您可以执行以下操作:

#!/bin/bash

# Iterate over files in the current directory
for file in * ; do

    # Skip directories
    if [ -d "$file" ] ; then
        continue
    fi

    # Print the filename
    echo -n "$file "

    # grep -o prints every match on a separate line
    # wc -l counts the lines
    grep -o 'STRING' "$file" | wc -l

done