3

I have an array ${sorted[@]}. How can I count the frequency of occurrence of the elements of the array.

e.g:

Array values:

bob
jane
bob
peter

Results:

bob 2
jane 1
peter 1

1 Answer 1

6

The command

(IFS=$'\n'; sort <<< "${array[*]}") | uniq -c

Explanation

  • Counting occurrences of unique lines is done with the idiom sort file | uniq -c.
  • Instead of using a file, we can also feed strings from the command line to sort using the here string operator <<<.
  • Lastly, we have to convert the array entries to lines inside a single string. With ${array[*]} the array is expanded to one single string where the array elements are separated by $IFS.
  • With IFS=$'\n' we set the $IFS variable to the newline character for this command exclusively. The $'...' is called ANSI-C Quoting and allows us to express the newline character as \n.
  • The subshell (...) is there to keep the change of $IFS local. After the command $IFS will have the same value as before.

Example

array=(fire air fire earth water air air)
(IFS=$'\n'; sort <<< "${array[*]}") | uniq -c

prints

      3 air
      1 earth
      2 fire
      1 water
Sign up to request clarification or add additional context in comments.

1 Comment

@user9487425 The old answer worked on bash 3.2 but not on bash 4.3 (wouldn't have expected that). I updated the answer to work on both versions.

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.