计算字符在unix中的字符串中出现的次数

时间:2015-12-30 19:57:33

标签: linux unix

无论如何都要计算一个字符在命令行的unix中出现在字符串中的次数。

例如:string =“Hello”“l” 这应该返回2

string =“hello”“k” 这应该返回0

string =“hello”“H” 这应该返回0

由于

3 个答案:

答案 0 :(得分:2)

在$ STRING中寻找角色我:

echo $STRING| grep -o I | wc -l

答案 1 :(得分:0)

使用带有字符串hello的Bash内置函数并查找'l'可以通过以下方式完成:

strippedvar=${string//[^l]/}
echo "char-count: ${#strippedvar}"

首先删除字符串中不同于l的所有字符 您显示剩余变量的长度。

替换中的lettter可以由var给出,如此循环所示:

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

答案 2 :(得分:0)

echo "Hello" | tr -cd "l" | wc -c

修剪删除补语“ l”;计算字符。

相关问题