posix sh: 如何在不使用外部工具的情况下计算字符串中出现的次数?

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

在bash中可以这样做:

#!/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\""

输出:

Found 3 occurences of "bengal"

当然需要注意的是,分隔符不能出现在 'query' 或 'string_to_search' 中。

在POSIX sh中,不支持字符串替换。有没有一种方法可以在 POSIX sh 中仅使用 shell 内置函数来完成?

我想我明白了...

#!/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\""
#!/bin/sh

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

ct() (
        n=0
        IFS=,
        q=
        set 
        for t in "$@"; do
                if [ "$t" = "$q" ]; then
                        n=$((n + 1))
                fi
        done
        echo $n
)

n=$(ct "$query" "$string_to_search")
printf "found %d %s\n" $n $query

虽然我不确定重点是什么。如果你有 posix shell, 您几乎肯定还有 printf、sed、grep 和 wc。

printf '%s\n' "$string_to_search" | sed -e 's/,/\n/g' | grep -Fx "$query" | wc -l