使用 Bash 计算字符串中字符的出现次数 [英] Count occurrences of a char in a string using Bash

查看:22
本文介绍了使用 Bash 计算字符串中字符的出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用 Bash 计算一个字符在字符串中出现的次数.

I need to count the number of occurrences of a char in a string using Bash.

在下面的例子中,当字符是(例如)t时,它echosvar 中的 >t,但是当字符为逗号或分号时,打印出零:

In the following example, when the char is (for example) t, it echos the correct number of occurrences of t in var, but when the character is comma or semicolon, it prints out zero:

var = "text,text,text,text" 
num = `expr match $var [,]`
echo "$num"

推荐答案

我会使用以下 awk 命令:

I would use the following awk command:

string="text,text,text,text"
char=","
awk -F"${char}" '{print NF-1}' <<< "${string}"

我用 $char 分割字符串并打印结果字段的数量减去 1.

I'm splitting the string by $char and print the number of resulting fields minus 1.

如果您的 shell 不支持 <<< 运算符,请使用 echo:

If your shell does not support the <<< operator, use echo:

echo "${string}" | awk -F"${char}" '{print NF-1}'

这篇关于使用 Bash 计算字符串中字符的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆