How to count item occurences in BASH array?

后端 未结 3 949
一整个雨季
一整个雨季 2021-01-14 22:12

I have an array ${myarr[@]} with strings. ${myarr[@]} basically consists of lines and each line constists of words.

world hello moo         


        
相关标签:
3条回答
  • 2021-01-14 22:19

    Try this:

    for word in ${myarr[*]}; do
      echo $word
    done | grep -c "hello"
    
    0 讨论(0)
  • 2021-01-14 22:27

    Alternative (without loop):

    grep -o hello <<< ${myarr[*]} | wc -l
    
    0 讨论(0)
  • 2021-01-14 22:37

    No need for an external program:

    count=0
    for word in ${myarr[*]}; do
        if [[ $word =~ hello ]]; then
            (( count++ ))
        fi
    done 
    
    echo $count
    
    0 讨论(0)
提交回复
热议问题