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.
</>
Copy
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
Example
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.
example.sh
</>
Copy
#!/bin/bash
str="hello world as world new world"
substr="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)
Output
sh-3.2# bash example.sh
Number of occurrences : 3
Conclusion
In this Bash Tutorial, we learned how to find the number of occurrences of substring in given string using echo
, grep
, and wc
commands.