且构网

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

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

更新时间:2022-12-12 12:17:56

有点 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

IFS=""读取 -r -a ids

输入:

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 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'