如何从Bash中的数组获取唯一值? [英] How can I get unique values from an array in Bash?
本文介绍了如何从Bash中的数组获取唯一值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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' ' '))
如果您的外壳支持此处字符串(应为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' ' '
输入:
ids=(aa ab aa ac aa ad)
输出:
aa ab ac ad
说明:
-
"${ids[@]}"
-使用shell数组的语法,无论是作为echo
的一部分还是在此处使用.@
部分的意思是数组中的所有元素" -
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屋!
查看全文