Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

bash

shell

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?

like image 894
user2436428 Avatar asked Oct 15 '15 16:10

user2436428


People also ask

How do you join two arrays?

In order to combine (concatenate) two arrays, we find its length stored in aLen and bLen respectively. Then, we create a new integer array result with length aLen + bLen . Now, in order to combine both, we copy each element in both arrays to result by using arraycopy() function.

Does bash have associative arrays?

Bash, however, includes the ability to create associative arrays, and it treats these arrays the same as any other array. An associative array lets you create lists of key and value pairs, instead of just numbered values.

How do I sort an array in bash?

Bubble sort works by swapping the adjacent elements if they are in the wrong order. Example: Given array - (9, 7, 2, 5) After first iteration - (7, 2, 5, 9) After second iteration - (2, 5, 7, 9) and so on... In this way, the array is sorted by placing the greater element at the end of the array.

What is associative array in bash?

3 years ago. An array variable is used to store multiple data with index and the value of each array element is accessed by the corresponding index value of that element. The array that can store string value as an index or key is called associative array.


2 Answers

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.

like image 109
chepner Avatar answered Sep 18 '22 06:09

chepner


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

like image 35
Steven Avatar answered Sep 22 '22 06:09

Steven