Count unique values in a bash array

假装没事ソ 提交于 2021-02-05 08:56:51

问题


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 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


来源:https://stackoverflow.com/questions/49263599/count-unique-values-in-a-bash-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!