Merging 2 Arrays

I am trying to create a script that combines 2 arrays:

#!/bin/bash
read -a unix    #(a c e g)
read -a test     #(b d f)

#now I want to merge ${unix[@]} with ${test[@]}, one after another such that the result would be: (abcdefg)
#I've tried quite a few options and can't seem to make it work

#! /bin/bash
read -a a1
read -a a2

len1=${#a1[@]}
len2=${#a2[@]}

[ $len1 -lt $len2 ] && len=$len2 || len=$len1

i=0
while [ $i -lt $len ]
do
    printf "%s %s " ${a1[$i]} ${a2[$i]}
    (( i++ ))
done
1 Like

A different approach would be

#!/bin/bash

unix=( a c e g )
test=( b d f )

printf "%s\n" ${unix[@]} >/tmp/1
printf "%s\n" ${test[@]} >/tmp/2

result=$( paste /tmp/1 /tmp/2 )
echo ${result[@]}
rm /tmp/1 /tmp/2

or shorter:

#!/bin/bash

unix=( a c e g )
test=( b d f )

result=$( paste <( printf "%s\n" ${unix[@]} ) <(printf "%s\n" ${test[@]}) )
echo ${result[@]}
1 Like

As you are using bash, here strings should be available. Try

sort <<<"$(echo ${unix[@]} ${test[@]}|tr ' ' '\n') "
a
b
c
d 
e
f
g

or, to get it into an array,

res=( $(sort <<<"$(echo ${unix[@]} ${test[@]}|tr ' ' '\n') ") )
1 Like

I think, that's not what the OP wants. I understood that he/she want's a sequence of unix[0], test[0], unix[1], test[1], etc., but I might be wrong.

1 Like

Yes, hergp, that is exactly what I am trying to do