5

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?

1
  • If there are multiple "hello"s on 1 line, grep -c will count that as 1 occurrence. Commented Mar 28, 2013 at 16:20

3 Answers 3

9

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)

Sign up to request clarification or add additional context in comments.

Comments

8

No need for an external program:

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

echo $count

Comments

5

Try this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.