Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell Script to Count the Occurrence of a Word in a file

Tags:

shell

Lets take the below content as an example

    This file is a test file 
    this file is used to count the word 'file' in this test file
    there are multiple occurrences of word file in some lines in this test file

I want to count the word 'file' in the above content.

I'm using the below shell command

   cat $filename |  sed "s/_/new/g" | sed "s/$word/_/g" | tr -c -d _ |wc -c

Is that ok or any better ideas ..?

like image 670
Manikandaraj Srinivasan Avatar asked Aug 06 '12 16:08

Manikandaraj Srinivasan


2 Answers

Using tr for separating words and then grep and wc seems possible :

tr -s ' ' '\n' < file.txt | grep file | wc -l
like image 95
Nibbler Avatar answered Oct 04 '22 04:10

Nibbler


grep $word $filename -o | wc -l
like image 37
Nykakin Avatar answered Oct 04 '22 02:10

Nykakin