简体   繁体   English

我们如何在Bash中获得两个数组的并集?

[英]How can we get the union of two arrays in Bash?

I've two arrays, say: 我有两个阵列,说:

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

What would be the best way to get union of these two arrays in Bash? 在Bash中将这两个数组联合起来的最佳方法是什么?

First, combine the arrays: 首先,组合数组:

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

Then, apply the solution from this post to deduplicate them: 然后,应用帖子中的解决方案对其进行重复数据删除:

# 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[@]}")

This assumes bash 4+. 这假设bash 4+。

Prior to bash 4, bash 4之前,

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

sort -u performs a dup-free union on its input; sort -u在其输入上执行无重复联合; the while loop just puts everything back in an array. while循环只是将所有内容放回到数组中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM