Use grep to quickly count occurrences of a string in a file

Here’s a neat one-liner for counting the number of times a string appears in a file.

cat myfile.txt | grep 'foo' -o | wc -l

This will print the number of times the string foo appears in myfile.txt.

Ofcourse, I could just open a modern text editor and use its find word feature but sometimes I just want to feel smart.

Sajad Torkamani

Hello! My name is Sajad. I’m a software developer at Nationwide and an aspiring entrepreneur. Originally from Afghanistan, I moved to London at an early age and have been living here for the past 20 years.

This is my personal website where I blog mostly about programming with occasional thoughts on a bunch of other things. I write mainly for my own benefit as I find that writing helps clarify my otherwise very confused thoughts.

Get in touch: sajadtorkamani1@gmail.com