Saturday, October 29, 2022

[SOLVED] Find the count of a specific keyword in multiple files in a directory

Issue

Say I have a directory /home/ and within it I have 3 subdirectories /home/red/ /home/blue/ /home/green/

And each subdirectory contains a file each like

/home/red/file1 /home/blue/file2 /home/green/file3

Now I want to find how many times file1,file2, file3 contains the word "hello" within them.

For example,

/home/red/file1 - 23
/home/blue/file2 - 6
/home/green/file3 - 0

Now, going to the locations of file and running the grep command is actually very inefficient when this problem scales.

I have tried using this grep command from the /home/ directory

grep -rnw '/path/to/somewhere/' -e 'pattern'

But this is just giving the occurrences rather than the count.

Is there any command through which I can get what I am looking for?


Solution

If the search term occurs at maximum once per line, you can use grep's -c option to report the count instead of the matching lines. So, the command will be grep -rc 'search' (add other options as needed).

If there can be more than one occurrence per line, I'd recommend using ripgrep. Note that rg recursively searches by default, so you can use something like rg -co 'search' from within the home directory (add other options as needed). Add --hidden if you need to search hidden files as well. Add --include-zero if you want to show files even if they didn't have any match.



Answered By - Sundeep
Answer Checked By - Marie Seifert (WPSolving Admin)