Count occurrences of a word in a file?
Tricky question. My friend came up with a request to count the number of occurrences of a word in a text file, without too much of a script. A single line solution? One that pops at the top of the head is grep -c. But that will fail if the word repeated within the line! With so many text processing commands in linux, I was left wondering what works easiest.
I haven’t used awk/sed/perl in a while. I could write him a python script in just about the typing time. But how should I do it without any of these? With the constraint that the words are separated by spaces, I ended up with this,
$ tr [:blank:] ['\n'] < file.txt | grep -c "pattern"
Seems to work. Not sure if there is an obvious mistake laughing at me. Maybe python can be harmful to your old linux habits!!
hey .. that is a neat command. .!
niq
July 24, 2008 at 11:10 pm
Helpful. Thanks
Shadi
June 26, 2009 at 7:50 am