且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从Bash中的数组获取唯一值?

更新时间:2022-12-12 12:26:59

有点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 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 Substitution
  • Aside: tr ' ' '\n' <<< "${ids[@]}" is a more efficient way of doing: echo "${ids[@]}" | tr ' ' '\n'