minerals
minerals

Reputation: 1315

How to count item occurences in BASH array?

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

world hello moon
weather dog tree
hello green plastic

I need to count the occurences of hello in this array. How do I do it?

Upvotes: 5

Views: 10927

Answers (3)

anishsane
anishsane

Reputation: 20970

Alternative (without loop):

grep -o hello <<< ${myarr[*]} | wc -l

Don't get tempted to change it to grep -oc hello. It counts the number of lines that contain hello. So, if some line contains more than 1 instances of the word, it will still be counted as 1.

Alternately, this would work too:

printf '%s\n' ${myarr[*]} | grep -cFx hello

The lack of quotes around ${myarr[*]} tokenizes it and printf will then print the words on separate lines. Then grep -c will count those.

Note:

The first approach will count a single word hello_some_string_here_hello as 2 instances of hello.
The second approach will count them as zero instances (match whole line with -x)

Upvotes: 9

cdarke
cdarke

Reputation: 44344

No need for an external program:

count=0
for word in ${myarr[*]}; do
    if [[ $word =~ hello ]]; then
        (( count++ ))
    fi
done 

echo $count

Upvotes: 7

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200193

Try this:

for word in ${myarr[*]}; do
  echo $word
done | grep -c "hello"

Upvotes: 5

Related Questions