如何计算 BASH 数组中的项目出现次数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15686881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 05:01:15 来源:igfitidea点击:
How to count item occurences in BASH array?
提问by minerals
I have an array ${myarr[@]}with strings. ${myarr[@]}basically consists of lines and each line constists of words.
我有一个${myarr[@]}带字符串的数组。${myarr[@]}基本上由行组成,每行由单词组成。
world hello moon
weather dog tree
hello green plastic
I need to count the occurences of helloin this array.
How do I do it?
我需要计算hello这个数组中的出现次数。我该怎么做?
回答by anishsane
Alternative (without loop):
替代方案(无循环):
grep -o hello <<< ${myarr[*]} | wc -l
回答by cdarke
No need for an external program:
无需外部程序:
count=0
for word in ${myarr[*]}; do
if [[ $word =~ hello ]]; then
(( count++ ))
fi
done
echo $count
回答by Ansgar Wiechers
Try this:
尝试这个:
for word in ${myarr[*]}; do
echo $word
done | grep -c "hello"

