计算bash数组中的唯一值 [英] Count unique values in a bash array
本文介绍了计算bash数组中的唯一值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数组 $ {sorted [@]}
.如何计算数组元素的出现频率.
I have an array ${sorted[@]}
. How can I count the frequency of occurrence of the elements of the array.
例如:
数组值:
bob
jane
bob
peter
结果:
bob 2
jane 1
peter 1
推荐答案
命令
(IFS=$'\n'; sort <<< "${array[*]}") | uniq -c
说明
- 对唯一行的出现进行计数是通过习惯用语
sort文件|来完成的.uniq -c
. - 代替使用文件,我们还可以使用 here字符串运算符
<< 代码>.
- 最后,我们必须将数组条目转换为单个字符串中的行.使用
$ {array [*]}
,数组可扩展为一个字符串,其中数组元素由$ IFS
分隔. - 使用
IFS = $'\ n'
,我们仅将$ IFS
变量设置为该命令的换行符.$'...'
称为 ANSI-C报价,它使我们可以将换行符表示为\ n
. - 子外壳
(...)
用于将$ codeS $ codeS的更改保持在本地.在命令$ IFS
之后将具有与以前相同的值. - 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.
Explanation
array=(fire air fire earth water air air)
(IFS=$'\n'; sort <<< "${array[*]}") | uniq -c
打印
3 air
1 earth
2 fire
1 water
这篇关于计算bash数组中的唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文