Sunday, June 5, 2022

[SOLVED] Shell Script to Count the Occurrence of a Word in a file

Issue

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 ..?


Solution

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

tr -s ' ' '\n' < file.txt | grep file | wc -l


Answered By - Nibbler
Answer Checked By - David Goodson (WPSolving Volunteer)