Unix:如何计算目录中所有文件中包含字符串的所有行并分别查看每个文件的输出

Unix: How can I count all lines containing a string in all files in a directory and see the output for each file separately

在 UNIX 中,我可以执行以下操作:

grep -o 'string' myFile.txt | wc -l

这将计算 myFile.txt 中包含该字符串的行数。 或者我可以使用 :

grep -o 'string' *.txt | wc -l

这将计算我的文件夹中包含该字符串的所有 .txt 扩展文件的行数。 我正在寻找一种方法来对文件夹中的所有文件进行计数,但要查看每个文件的输出分离,例如:

myFile.txt 10000

myFile2.txt 20000

myFile3.txt 30000

我希望我已经说清楚了,如果没有,您可以在 :

的输出中看到一个比较接近的示例
wc -l *.txt

为什么不简单地使用计算匹配行的 grep -c?根据 GNU grep manual,它甚至在 POSIX 中,因此几乎可以在任何地方使用。

顺便说一句,您对 -o 的使用使您的命令计算字符串的每一次出现,而不是每一行出现的任何情况:

$ cat > testfile
hello hello
goodbye
$ grep -o hello testfile
hello
hello

并且您正在进行正则表达式搜索,这可能与字符串搜索不同(请参阅字符串搜索的 -F 标志)。

对所有文件使用循环,例如

for f in *.txt; do echo -n $f $'\t'; echo grep 'string' "$f" | wc -l; done

但我必须承认@Yann 的 grep -c 更简洁:-)。不过,循环对于更复杂的事情可能很有用。