69

What is an easy way to count the number of times a word appears in a file?

2
  • 2
    How do you define 'word'? Is it just a string, or a string surrounded by spaces, a string surrounded by a set of characters? What characters can these be? Commented Feb 3, 2011 at 18:11
  • a 48 charactors string, no space and no special charactors other than ascii Commented Feb 3, 2011 at 18:19

3 Answers 3

152

This will also count multiple occurrences of the word in a single line:

grep -o 'word' filename | wc -l 
Sign up to request clarification or add additional context in comments.

7 Comments

Ahh, the -o does the magic. Nice answer, never knew that. No more upvotes today though :(
past the test, why cat the file, then it count the multiple word on the same line?
the reason i want to know is for the performence since we have large log files lots of them to count those jsession id, very painful, need count those fast, but well done, so far i like this one the best, thx mohit6up!
Good Answer: I don't see this documented in man. How did you find out ?
grep -ow word file | wc -l if you care for word boundaries.
|
3
cat filename | tr ' ' '\n' | grep 'word' | wc -l 

1 Comment

This approach is very inefficient. cat is not really needed here. tr ' ' '\n' < filename | grep -cw 'word' would do.
-1
fgrep "word to be counted" filename|wc -w 

2 Comments

While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.
This doesn't do what OP wants.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.