如何计算Bash字符串中char出现的次数

时间:2018-12-01 11:10:37

标签: string bash shell grep character

这是代码:

#bash/bin
echo "Enter a sentence:"
read -e -a sentence
char="k"
echo "${sentence}" | awk -F"${char}" '{print NF-1}'

问题:

它返回此错误:

  

':不是有效的标识符句子-1

样本输入

Enter a sentence:
thanks and okay

示例输出

2

问题:

我该如何解决?

2 个答案:

答案 0 :(得分:1)

只需剥离所有 $char,然后计算结果即可。

echo "Enter a sentence:"
read -e sentence
char="k"
filtered=${sentence//[^$char]/}  # Delete anything *not* a $char
echo "${#filtered}"              # Output the length of filtered

使用标准外壳,您需要一对外部实用程序而不是bash的参数替换运算符。

echo "$sentence" | tr -cd "$char" | wc -c

答案 1 :(得分:0)

fun bar f g a = case (g a) of
                true => (f a)
                | false => a;

fun bari f g a = (fn true => f a | false => a)(g a);