Get word count in all files

I have a directory tree with a bunch of folders and subfolders in it and a bunch of files in these subfolders. I need to get the number of words "Hello" in each of these files and display the result as "File" a "has" "Hello" n times "," File "b has" Hello "m times" etc. How to write The script is on linux so that I can get the word count for the word hello in each of these files. I tried some combinations of grep with "wc" after browsing over the net, but this gave me the total number of all files in all folders.

thanks

+4
source share
2 answers

Try something like this:

find . -type f | xargs -n1 grep "Hello" -c

Adding -type f to find ensures that it returns files, not directories. Adding -n1 to -n1 that each file returned by find gets its own grep call so you can get a bill for each file. The -c argument to grep returns the number of matches instead of each match.

The above expression will count the number of lines that have "Hello" in it. If you need the total number of Hellos, and not just the number of lines that contain Hello, you need to do something more complex. You can use the -o option in grep to just print the corresponding section of the line, and then combine this with wc -l to get the number of total occurrences.

+2
source

Using grep , the syntax is:

 grep -Rc "Hello" your_dir/ 

I also recommend ack as a great replacement for grep :

 ack -lc "Hello" your_dir/ 
0
source

Source: https://habr.com/ru/post/1442634/


All Articles