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?
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.
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.
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.
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.
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.
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+.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With