Monday, November 28, 2016

Unix Bash - How to count occurrences of a word in a text file

Suppose you are interested in the number of occurrences of the word "foo" in your local file "mytextfile.xyz", then the following command will display the number of instances of the word "foo":

$ grep -o "\bfoo\b" ./mytextfile.xyz |  wc -l

How it works

Two shell programs are being used:

  1. grep
  2. wc

grep -Eoh "\bfoo\b"

Reads the file and looks for the regular expression \bfoo\b, the flag -o is used to print only the matching part of the lines (and not the whole line). The result is a sequence of lines with just the word "foo".

foo
foo
foo
...

wc -l

The result of the grep command is then piped to the command wc -l where the flag -l is used to only return the number of lines.

No comments:

Post a Comment