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

五迷三道 提交于 2019-11-26 11:37:59

问题


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.


回答1:


Assuming both arrays are the same size,

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



回答2:


I've found more common the case where I want to zip two arrays into two columns. This isn't as natively Zsh as the "RTLinuxSW" answer, 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 can shove that into another array to get the intended output:

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



回答3:


You can easily read the files, create an array with their content, check who is the bigger one and make the 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 -> It creates an array

declare -i -> It declares the var as integer

${#FILE01[@]} -> It's to get the array size



来源:https://stackoverflow.com/questions/30721317/how-to-merge-two-arrays-in-a-zipper-like-fashion-in-bash

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!