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

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

问题描述

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

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

在下面的示例中,当char是(例如)t时,它 echo s var中出现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命令:

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.

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

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

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

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

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