string=hello
for ch in a b c d e f g h i j k l m; do
strippedvar=${string//[^$ch]/}
echo "The letter ${ch} occurs ${#strippedvar} times"
done
输出值:
The letter a occurs 0 times
The letter b occurs 0 times
The letter c occurs 0 times
The letter d occurs 0 times
The letter e occurs 1 times
The letter f occurs 0 times
The letter g occurs 0 times
The letter h occurs 1 times
The letter i occurs 0 times
The letter j occurs 0 times
The letter k occurs 0 times
The letter l occurs 2 times
The letter m occurs 0 times
5条答案
按热度按时间qmelpv7a1#
另一个不同的解决方案
我想如果你只想要“l”的话。
wnvonmuf2#
在$STRING中查找字符l:
gg0vcinb3#
修剪删除“l”的恭维语;计算字符数。
vsikbqxv4#
使用Bash内置字符串hello并查找'l'可以通过以下方式完成:
首先,从字符串中删除所有不同于l的字符。
显示剩余变量的长度。
替换中的变量可以由var给出,如下面的循环所示:
输出值:
mkshixfv5#
一句话回答