12

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?

codeforester
  • 39,467
  • 16
  • 112
  • 140
user2436428
  • 1,653
  • 3
  • 17
  • 23

2 Answers2

12

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+.

Community
  • 1
  • 1
Steven
  • 5,654
  • 1
  • 16
  • 19
3

Prior to 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; the while loop just puts everything back in an array.

chepner
  • 497,756
  • 71
  • 530
  • 681