Use grep to quickly count occurrences of a string in a file
September 2, 2020 (Updated April 14, 2021)
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
.
This is useful when you need to count string occurrences as part of some script.
Tagged:
Unix