Bash – Find number of occurrences of substring in string

To find number of occurrences of a substring in a string in Bash scripting, you can use echo, grep, and wc command, as shown in the following expression.

echo "$str" | grep -o "$substr" | wc -l
  • echo displays the given string str
  • grep -o options is used to print only the matched parts, each on a separate line
  • wc -l prints the newline counts


In the following script, we take a string in str and substring in substr. We count the number of occurrences of substring substr in string str, using the above specified expression.


str="hello world as world new world"
count=$(echo "$str" | grep -o "$substr" | wc -l)
echo "Number of occurrences : $count"

Bash Version: GNU bash, version 5.2.15(1)-release (aarch64-apple-darwin22.1.0)


sh-3.2# bash 
Number of occurrences :        3


In this Bash Tutorial, we learned how to find the number of occurrences of substring in given string using echo, grep, and wc commands.