我需要知道给定字符出现在字符串中的次数。
该解决方案应能够在大多数Posix兼容的外壳解释器下运行,并且应尽可能少。
这是一个仅取决于 echo
, tr
, test
和 ${#
的壳函数:
charcount() {
local char="$1"; shift;
result="$(echo "$*" | tr -cd "$char")"; result=${#result};
test $result -gt 0 && echo $result
}
用法示例:
# charcount 'a' 'test' || echo 'char not found'
char not found
# charcount 'a' 'a test a' && echo 'found'
2
found
这是一个更具体的解决方案,只能测试字符符中是否存在。
charexists() { test "$(echo "$2" | tr -cd "$1")" ;}