Merging two arrays in Bash

Viewed 65417

I have two arrays A and B. I want to combine them into a new array C, which is their Cartesian product:

A=( 0 1 )
B=( 1 2 )

# Desired output:
C=( 0:1 0:2 1:1 1:2 )

I tried:

   for ((z = 0; z <= ${#A[@]}; z++)); do
     for ((y = 0; y <= ${#B[@]}; y++)); do
       C[$y + $z]="${A[$z]}:"
       C[$y + $z + 1]="${B[$y]}"
     done
   done

But that outputs:

 0: : : :

I expected 0:1 0:2 for A = ( 0 ) and B = ( 1 2 ).

5 Answers

Since Bash supports sparse arrays, it's better to iterate over the array than to use an index based on the size.

a=(0 1); b=(2 3)
i=0
for z in ${a[@]}
do
    for y in ${b[@]}
    do
        c[i++]="$z:$y"
    done
done
declare -p c   # dump the array

Outputs:

declare -a c='([0]="0:2" [1]="0:3" [2]="1:2" [3]="1:3")'

here's one way

a=(0 1)
b=(1 2)
for((i=0;i<${#a[@]};i++));
do
    for ((j=0;j<${#b[@]};j++))
    do
        c+=(${a[i]}:${b[j]});
    done
done

for i in ${c[@]}
do
    echo $i
done

Here is how I merged two arrays in Bash:

Example arrays:

AR=(1 2 3) BR=(4 5 6)

One Liner:

CR=($(echo ${AR[*]}) $(echo ${BR[*]}))

One line statement to merge two arrays in bash:

combine=( `echo ${array1[@]}` `echo ${array2[@]}` )
Related