${myarr[@]}
我有一个带字符串的数组。${myarr[@]}
基本上由行组成,每行由单词组成。
world hello moon
weather dog tree
hello green plastic
我需要计算hello
这个数组中的出现次数。我该怎么做?
替代方案(无循环):
grep -o hello <<< ${myarr[*]} | wc -l
无需外部程序:
count=0
for word in ${myarr[*]}; do
if [[ $word =~ hello ]]; then
(( count++ ))
fi
done
echo $count
试试这个:
for word in ${myarr[*]}; do
echo $word
done | grep -c "hello"