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
(IFS=$'\n'; sort <<< "${array[*]}") | uniq -c
sort file | uniq -c.sort using the here string operator <<<.${array[*]} the array is expanded to one single string where the array elements are separated by $IFS.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.(...) is there to keep the change of $IFS local. After the command $IFS will have the same value as before.array=(fire air fire earth water air air)
(IFS=$'\n'; sort <<< "${array[*]}") | uniq -c
prints
3 air
1 earth
2 fire
1 water