Tech Talk

Linux, Python, E51, Scripting…

Count occurrences of a word in a file?

with 2 comments

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!!

Blogged with the Flock Browser

Tags: , , , , , ,

Written by abiya

April 29, 2008 at 6:35 am

Posted in python, samples, technical

2 Responses

Subscribe to comments with RSS.

  1. hey .. that is a neat command. .!

    niq

    July 24, 2008 at 11:10 pm

  2. Helpful. Thanks

    Shadi

    June 26, 2009 at 7:50 am


Leave a Reply