What is an easy way to count the number of times a word appears in a file?
- 2How 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?abesto– abesto2011-02-03 18:11:12 +00:00Commented Feb 3, 2011 at 18:11
- a 48 charactors string, no space and no special charactors other than asciimagqq– magqq2011-02-03 18:19:05 +00:00Commented Feb 3, 2011 at 18:19
Add a comment |
3 Answers
This will also count multiple occurrences of the word in a single line:
grep -o 'word' filename | wc -l 7 Comments
magqq
past the test, why cat the file, then it count the multiple word on the same line?
magqq
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!
aartist
Good Answer: I don't see this documented in man. How did you find out ?
codeforester
grep -ow word file | wc -l if you care for word boundaries. |
cat filename | tr ' ' '\n' | grep 'word' | wc -l 1 Comment
codeforester
This approach is very inefficient.
cat is not really needed here. tr ' ' '\n' < filename | grep -cw 'word' would do.fgrep "word to be counted" filename|wc -w 2 Comments
Badacadabra
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.
codeforester
This doesn't do what OP wants.