I have a string which looks like this:
STRING="$PATTERN_some-stuff_$PATTERN_some-other_stuff"
I would like to count the number of occurences of $PATTERN in it, only with Bash builtin commands.
The more straightforward way of doing this I have found so far is to extract from the string only the strings that match $PATTERN, and then to count how many occurrences of $PATTERN there are in the newly created string, proceeding this way:
expr length "${STRING//[^$PATTERN]}" / ${#PATTERN}
But it only works if $PATTERN is a single character. I tried to use the syntax ${STRING//!(PATTERN)}", which would, if I understand well Bash manual, only match $PATTERN at the exclusion of the rest of $STRING, but it actually outputs nothing. So, where am I wrong ?
If you’re a bit flexible about builtins only, this is a perfect situation for
grep -o: