How to combine two arrays into a zipper, like a mod in Bash?

I am trying to combine two arrays into one, like a zipper. I have difficulty making this happen.

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

I tried using nested for loops but can't figure it out. I do not want the output to be 13572468, but 12345678.

The script I'm working on is here ( http://ix.io/iZR ) .. but it clearly doesn't work as intended. I either get the entire array2 (e.g. 124683), or just the first index, as if the loop weren’t working (e.g. 12325272).

So how do I get the output:

 one two three four five six seven eight 

with the two above arrays?

Change: I managed to solve this with two for and paste loops ( http://ix.io/iZU ). It would still be interesting to see if anyone has a better solution. So if you have time, please take a look.

+9
arrays bash zsh
source share
3 answers

Assuming both arrays are the same size,

 unset result for (( i=0; i<${#array1[*]}; ++i)); do result+=( ${array1[$i]} ${array2[$i]} ); done 
+7
source share

I found a more common case where I want to freeze two arrays into two columns. This is not like Zsh as the answer "RTLinuxSW", but for this case, I use paste.

 % tabs 16 % paste <(print -l $array1) <(print -l $array2) one two three four five six seven eight 

And then it can cram it into another array to get the required output:

 % array3=( `!!`«tab»«tab» ) % print $array3 one two three four five six seven eight 
+3
source share

You can easily read files, create an array with their contents, check which one is larger, and make a loop.

 #!/usr/bin/env bash ## Writting a until d into the file file01 and writing 1 until 3 into the file file02. echo {a..d} | tee file01 echo {1..3} | tee file02 ## Declaring two arrays (FILE01 and FILE02) and a variable as integer. declare -a FILE01=($(<file1)) declare -a FILE02=($(<file2)) declare -i COUNT=0 ## Checking who is the biggest array and declaring the ARRAY_SIZE. [[ "${#FILE01[@]}" -ge "${#FILE02[@]}" ]] && declare -i ARRAY_SIZE="${#FILE01[@]}" || declare -i ARRAY_SIZE="${#FILE02[@]}" ## Creating the loop (COUNT must be lesser or equal ARRAY_SIZE) and print each element of each array (FILE01 and FILE02). while [ ${COUNT} -le ${ARRAY_SIZE} ]; do echo -n "${FILE01[$COUNT]} ${FILE02[$COUNT]} " ((COUNT++)) done 

declare -a Creates an array

declare -i It declares a variable as an integer.

${#FILE01[@]} → this is to get the size of the array

0
source share

All Articles