我有一个目录树,其中包含一堆文件夹和子文件夹,以及这些子文件夹中的一堆文件。我需要在每个文件中获取单词'Hello'的计数并将结果显示为'文件'a'有'Hello'n次','文件'b'有'Hello'm次'等等. 我如何在 linux 中编写脚本,以便我可以在每个文件中获取单词 hello 的字数。浏览 net 后,我尝试了一些 grep 与 'wc' 的组合,但这给了我所有文件夹中所有文件的总数。
谢谢
Try something like this:
find . -type f | xargs -n1 grep "Hello" -c
Adding -type f
to find
ensures that it only returns files, not directories. Adding -n1
to xargs
makes it so that every file returned by find
gets its own invocation of grep
, so that you can get a per-file count. The -c
argument to grep
returns the count of matches instead of every match.
The above expression will count the number of lines that have 'Hello' in them. If you need the total number of Hellos, instead of just the number of lines that have Hello in them, you'll need to do something more sophisticated. You can use the -o
option on grep to just print the matching section of a line, and then combine that with wc -l
to get the number of total occurrences.