Unix / Linux: grep Word Count Command

In Unix or Linux, you can use the grep command to count the number of occurrences of a word in a file. Here’s how:

  1. Open a terminal window and navigate to the directory where the file you want to search is located using the cd command.
  2. Use the following command to count the number of occurrences of a word in a file:
    grep -o -w "word" file | wc -l

    Replace word with the actual word you want to search for, and replace file with the actual name of the file you want to search.

  3. The output will be the number of times the word appears in the file.

Note: The grep command has many options and flags that can be used to modify its behavior. The -o option causes grep to only print the matching parts of the line, while the -w option causes grep to match only whole words, not just substrings. The wc command is used to count the number of lines, words, and characters in a file. The -l option to wc causes it to only print the number of lines.

Leave a Comment