Search code examples
shposix

posix sh: how to count number of occurrences in a string without using external tools?


In bash, it can be done like this:

#!/bin/bash

query='bengal'
string_to_search='bengal,toyger,bengal,persian,bengal'

delimiter='|'

replace_queries="${string_to_search//"$query"/"$delimiter"}"

delimiter_count="${replace_queries//[^"$delimiter"]}"
delimiter_count="${#delimiter_count}"

echo "Found $delimiter_count occurences of \"$query\""

Output:

Found 3 occurences of "bengal"

The caveat of course is that the delimiter cannot occur in 'query' or 'string_to_search'.

In POSIX sh, string replacement is not supported. Is there a way this can be done in POSIX sh using only shell builtins?


Solution

  • Think I got it...

    #!/bin/sh
    
    query='bengal'
    string_to_search='bengal,toyger,bengal,persian,bengal'
    
    i=0
    process_string="$string_to_search"
    while [ -n "$process_string" ]; do
        case "$process_string" in
            *"$query"*)
                process_string="${process_string#*"$query"}"
                i="$(( i + 1 ))"
                ;;
            *)
                break
                ;;
        esac
    done
    
    echo "Found $i occurences of \"$query\""