如何从 Bash 中的数组中获取唯一值? [英] How can I get unique values from an array in Bash?
问题描述
我遇到了与 此处.
我有一个包含 aa ab aa ac aa ad
等的数组.现在我想从这个数组中选择所有唯一的元素.想,这会很简单 sort |uniq
或 sort -u
正如他们在另一个问题中提到的那样,但数组中没有任何变化......代码是:
I have an array which contains aa ab aa ac aa ad
, etc.
Now I want to select all unique elements from this array.
Thought, this would be simple with sort | uniq
or with sort -u
as they mentioned in that other question, but nothing changed in the array...
The code is:
echo `echo "${ids[@]}" | sort | uniq`
我做错了什么?
推荐答案
有点 hacky,但这应该可以:
A bit hacky, but this should do it:
echo "${ids[@]}" | tr ' ' '\n' | sort -u | tr '\n' ' '
要将排序后的唯一结果保存回数组,请执行数组分配:
To save the sorted unique results back into an array, do Array assignment:
sorted_unique_ids=($(echo "${ids[@]}" | tr ' ' '\n' | sort -u | tr '\n' ' '))
如果你的 shell 支持 herestrings (bash
应该),您可以将 echo
进程更改为:
If your shell supports herestrings (bash
should), you can spare an echo
process by altering it to:
tr ' ' '\n' <<< "${ids[@]}" | sort -u | tr '\n' ' '
截至 2021 年 8 月 28 日的说明:
根据ShellCheck wiki 2207 a read -a
应使用管道以避免分裂.因此,在 bash 中,命令将是:
According to ShellCheck wiki 2207 a read -a
pipe should be used to avoid splitting.
Thus, in bash the command would be:
IFS=""读取 -r -a ids <<<"$(echo "${ids[@]}" | tr ' ' '\n' | sort -u | tr '\n' ' ')"
或
IFS=""读取 -r -a ids <<<"$(tr ' ' '\n' <<< "${ids[@]}" | sort -u | tr '\n' ' ')"
输入:
ids=(aa ab aa ac aa ad)
输出:
aa ab ac ad
说明:
"${ids[@]}"
- 用于处理 shell 数组的语法,无论是用作echo
的一部分还是用作 herestring.@
部分表示数组中的所有元素"tr ' ' '\n'
- 将所有空格转换为换行符.因为你的数组被 shell 看作是一行上的元素,用空格分隔;并且因为 sort 期望输入在不同的行上.sort -u
- 排序并只保留唯一元素tr '\n' ' '
- 将我们之前添加的换行符转换回空格.$(...)
- 命令替换- 旁白:
tr ' ' '\n' <<<${ids[@]}"
是一种更有效的方式:echo ${ids[@]}"|tr ' ' '\n'
"${ids[@]}"
- Syntax for working with shell arrays, whether used as part ofecho
or a herestring. The@
part means "all elements in the array"tr ' ' '\n'
- Convert all spaces to newlines. Because your array is seen by shell as elements on a single line, separated by spaces; and because sort expects input to be on separate lines.sort -u
- sort and retain only unique elementstr '\n' ' '
- convert the newlines we added in earlier back to spaces.$(...)
- Command Substitution- Aside:
tr ' ' '\n' <<< "${ids[@]}"
is a more efficient way of doing:echo "${ids[@]}" | tr ' ' '\n'
这篇关于如何从 Bash 中的数组中获取唯一值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!