如何从在Linux bash的数组获得唯一值? [英] How can I get unique values from an array in linux bash?

查看:451
本文介绍了如何从在Linux bash的数组获得唯一值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得差不多<一个同样的问题href=\"http://stackoverflow.com/questions/618378/select-unique-or-distinct-values-from-a-list-in-unix-shell-script\">here.

我有一个包含 AA AB AA AC AA广告的阵列等
现在,我要选择从这个阵列中的所有独特的元素。
认为,这将是简单的用排序| uniq的排序-u ,因为他们在其他问题中提到,但没有在数组中改变...
在code是:

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`

我在做什么错了?

What am I doing wrong?

推荐答案

一个有点哈克,但这应该这样做:

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:

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

如果你的外壳支持 herestrings 庆典应),你可以通过它改变腾出一个回声流程:

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 [@]} - 语法与壳牌阵列的工作,无论是作为的一部分回声或herestring。在 @ 部分是指数组中的所有元素

  • TR''的'\\ n' - 转换所有空格换行。因为你的阵列是由外壳作为单行线,用空格隔开的元素可见;因为排序预计投入将在单独的行。

  • 排序-u - 排序,只保留独特的元素

  • TR的'\\ n''' - 转换成我们在前面回空间添加新行

  • $(...) - 命令Subsitution

  • 旁白: TR''的'\\ n'&LT;&LT;&LT; $ {IDS [@]}是做的更有效的方式:回声$ {IDS [@]}| TR''的'\\ n'

  • "${ids[@]}" - Syntax for working with shell arrays, whether used as part of echo 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 elements
  • tr '\n' ' ' - convert the newlines we added in earlier back to spaces.
  • $(...) - Command Subsitution
  • Aside: tr ' ' '\n' <<< "${ids[@]}" is a more efficient way of doing: echo "${ids[@]}" | tr ' ' '\n'

这篇关于如何从在Linux bash的数组获得唯一值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆