Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge two arrays in a zipper like fashion in Bash?

Tags:

arrays

bash

zsh

I am trying to merge two arrays into one in a zipper like fashion. I have difficulty to make that happen.

array1=(one three five seven)
array2=(two four six eight)

I have tried with nested for-loops but can't figure it out. I don't want the output to be 13572468 but 12345678.

The actual script I am working on is here (http://ix.io/iZR).. but it is obviously not working as intended. I either get the whole of array2 printed (ex. 124683) or just the first index like if the loop didn't work (ex. 12325272).

So how do I get the output:

one two three four five six seven eight

with above two arrays?

Edit: I was able to solve it with two for-loops and paste (http://ix.io/iZU). It would still be interesting to see if someone have a better solution. So if you have time please take a look.

like image 874
AlMehdi Avatar asked Jun 09 '15 00:06

AlMehdi


People also ask

How do I merge two arrays together?

The concat() method concatenates (joins) two or more arrays. The concat() method returns a new array, containing the joined arrays. The concat() method does not change the existing arrays.

What is merging two arrays?

Merging two arrays means combining two separate arrays into one single array. For instance, if the first array consists of 3 elements and the second array consists of 5 elements then the resulting array consists of 8 elements. This resulting array is known as a merged array.


1 Answers

Assuming both arrays are the same size,

unset result
for (( i=0; i<${#array1[*]}; ++i)); do
    result+=( "${array1[$i]}" "${array2[$i]}" )
done
like image 186
RTLinuxSW Avatar answered Oct 06 '22 09:10

RTLinuxSW