user9487425
user9487425

Reputation: 33

Count unique values in a bash array

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

Upvotes: 3

Views: 3519

Answers (1)

Socowi
Socowi

Reputation: 27195

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

Upvotes: 6

Related Questions