Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining word count using grep (in cases where there are multiple words in a line)

Is it possible to determine the number of times a particular word appears using grep

I tried the "-c" option but this returns the number of matching lines the particular word appears in

For example if I have a file with

some words and matchingWord and matchingWord

and then another matchingWord

running grep on this file for "matchingWord" with the "-c" option will only return 2 ...

note: this is the grep command line utility on a standard unix os

like image 730
sachin Avatar asked Oct 09 '11 06:10

sachin


People also ask

How do I count words using grep?

Using grep -c alone will count the number of lines that contain the matching word instead of the number of total matches. The -o option is what tells grep to output each match in a unique line and then wc -l tells wc to count the number of lines. This is how the total number of matching words is deduced.

How do you count the number of occurrences of words in a text file?

To count the number of occurrences of a specific word in a text file, read the content of text file to a string and use String. count() function with the word passed as argument to the count() function.

How use grep command to find a string in multiple files?

To search multiple files with the grep command, insert the filenames you want to search, separated with a space character. The terminal prints the name of every file that contains the matching lines, and the actual lines that include the required string of characters. You can append as many filenames as needed.


1 Answers

grep -o string file will return all matching occurrences of string. You can then do grep -o string file | wc -l to get the count you're looking for.

like image 139
knite Avatar answered Oct 08 '22 19:10

knite