【问题标题】:How can we get the union of two arrays in Bash?我们如何在 Bash 中获得两个数组的并集?
【发布时间】:2016-01-14 05:16:03
【问题描述】:

我有两个数组,比如说:

arr1=("one" "two" "three")
arr2=("two" "four" "six")

在 Bash 中合并这两个数组的最佳方法是什么?

【问题讨论】:

  • 实际联合(没有重复)或只是两个数组串联?
  • 实际并集(不重复)
  • 在zsh中你可以使用typeset -U arr,很确定在bash中没有这么简单的方法。
  • @Kevin 如何使用typeset -U arr?
  • @denysdovhan typeset -u arr; arr=(a b a c); echo $arr # prints a b c.

标签: linux bash shell


【解决方案1】:

首先,合并数组:

arr3=("${arr1[@]}" "${arr2[@]}")

然后,应用this 帖子中的解决方案对它们进行重复数据删除:

# Declare an associative array
declare -A arr4
# Store the values of arr3 in arr4 as keys.
for k in "${arr3[@]}"; do arr4["$k"]=1; done
# Extract the keys.
arr5=("${!arr4[@]}")

这假设 bash 4+。

【讨论】:

  • 不需要arr3:只需使用for k in "${arr1[@]}" "${arr2[@]}"
【解决方案2】:

bash4 之前,

while read -r; do
    arr+=("$REPLY")
done < <( printf '%s\n' "${arr1[@]}" "${arr2[@]}" | sort -u )

sort -u 对其输入执行无重复联合; while 循环只是将所有内容放回数组中。

【讨论】:

    猜你喜欢
    • 2015-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-23
    • 2010-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多