簡體   English   中英

我們如何在Bash中獲得兩個數組的並集?

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

我有兩個陣列,說:

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

在Bash中將這兩個數組聯合起來的最佳方法是什么?

首先,組合數組:

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

然后,應用帖子中的解決方案對其進行重復數據刪除:

# 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+。

bash 4之前,

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

sort -u在其輸入上執行無重復聯合; while循環只是將所有內容放回到數組中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM