How to Count Words in A Unix Line

by on March 11, 2010

in consumer

The other day I was trying to figure out how to count the number of words in a text line in unix.

My issue is that I was editing a specific “field” with a PERL command, but I was worried that in the off chance the numerical variable occurred more than once, in places I wasn’t expecting, my efforts to replace the variable could go horribly wrong and I could end up replacing all the wrong occurrences of where the variable occurred.

I tried hunting it down but it took forever to find any references.  Most that I found actually didn’t work.  But then I found this little trick.

I hope it helps you count how many times a word or variable occur in a sentence!

$ echo “dog dog” | tr ” ” “\n” | grep -c “dog”

2

Now I leave it up to you to figure out how to apply this little trick to your own project!

A Thought:  The other day…  I should name my how to’s that… “The Other Day” series, because I seem to always start these that way!

Related posts

Leave a Comment

Previous post:

Next post: