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

I have two arrays, let's say:

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

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

+7
linux bash shell
source share
2 answers

Combine arrays first:

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

Then apply the solution from this for deduplication:

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

+9
source share

Before bash 4,

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

sort -u performs the join without duplication at its input; while just returns everything to an array.

+2
source share

All Articles