问题
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:
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
sortusing 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$IFSvariable 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$IFSlocal. After the command$IFSwill 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
来源:https://stackoverflow.com/questions/49263599/count-unique-values-in-a-bash-array