如何排序并从 bash 中的数组中获取唯一值?

How to sort and get unique values from an array in bash?

我是 bash 脚本编写的新手...我正在尝试对一个数组中的唯一值进行排序并将其存储到另一个数组中。 例如:

list=('a','b','b','b','c','c');

我需要,

unique_sorted_list=('b','c','a')

我尝试了一些东西,没有帮助我..

sorted_ids=($(for v in "${ids[@]}"; do echo "$v";done| sort| uniq| xargs))

sorted_ids=$(echo "${ids[@]}" | tr ' ' '\n' | sort -u | tr '\n' ' ')

你们能帮帮我吗....

尝试:

$ list=(a b b b c c)
$ unique_sorted_list=($(printf "%s\n" "${list[@]}" | sort -u))
$ echo "${unique_sorted_list[@]}"
a b c

根据评论更新:

$ uniq=($(printf "%s\n" "${list[@]}" | sort | uniq -c | sort -rnk1 | awk '{ print  }'))

如果数组元素包含空格,则接受的答案无效。

试试这个:

readarray -t unique_sorted_list < <( printf "%s\n" "${list[@]}" | sort -u )

在Bash中,readarray是内置mapfile命令的别名。有关详细信息,请参阅 help mapfile

-t 选项是从读取的每一行中删除结尾的换行符(在 printf 中使用)。