How to count total number of word occurrences using grep on Linux or Unix
I want to find out how many times a word (say foo or an IP address) occurs in a text file using the grep command on Linux or Unix-like system?
You can use the grep command to search strings, words, text, and numbers for a given patterns. You can pass the -c option to grep command. It only shows the number of times that the pattern has been matched for each file.
Show the total number of times that the word foo appears in a file named bar.txt
The syntax is: grep -c string filename grep -c foo bar.txt Sample outputs:
To count total number of occurrences of word in a file named /etc/passwd root using grep, run: grep -c root /etc/passwd To verify that run: grep --color root /etc/passwd Pass the -w option to grep to select only an entire word or phrase that matches the specified pattern: grep -w root /etc/passwd OR grep -c -w root /etc/passwd In this example only match a word being with root: grep --color -w '^root' /etc/passwd grep -c -w '^root' /etc/passwd To show only the matching part of the lines. grep -o 'root' /etc/passwd grep -c -o 'root' /etc/passwd Sample session:
The author is the creator of nixCraft and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.