f10bit
f10bit

Reputation: 19760

Merging two Bash arrays into key:value pairs via a Cartesian product

I have two arrays A and B. How do I combine them into a new array C, which is their Cartesian product? For example, given:

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

Desired output:

C=( 0:1 0:2 1:1 1:2 )

Upvotes: 53

Views: 80418

Answers (5)

Ian Dunn
Ian Dunn

Reputation: 3680

If you don't care about having duplicates, or maintaining indexes, then you can concatenate the two arrays in one line with:

NEW=("${OLD1[@]}" "${OLD2[@]}")

Full example:

Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux');
Shell=('bash' 'csh' 'jsh' 'rsh' 'ksh' 'rc' 'tcsh');
UnixShell=("${Unix[@]}" "${Shell[@]}")
echo ${UnixShell[@]}
echo ${#UnixShell[@]}

Credit: http://www.thegeekstuff.com/2010/06/bash-array-tutorial/

Upvotes: 159

Joel Zamboni
Joel Zamboni

Reputation: 345

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[*]}))

Upvotes: 0

Suresh N S
Suresh N S

Reputation: 9

One line statement to merge two arrays in bash:

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

Upvotes: -2

Dennis Williamson
Dennis Williamson

Reputation: 359965

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")'

Upvotes: 20

ghostdog74
ghostdog74

Reputation: 342333

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

Upvotes: 5

Related Questions