我们如何在Bash中获得两个数组的并集? [英] How can we get the union of two arrays in Bash?

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

问题描述

我有两个数组,说:

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

在Bash中将这两个数组结合起来的最佳方法是什么?

What would be the best way to get union of these two arrays in Bash?

推荐答案

首先,合并数组:

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

假设bash为4 +.

This assumes bash 4+.

这篇关于我们如何在Bash中获得两个数组的并集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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