如何在 Bash 中像时尚一样在拉链中合并两个数组? [英] How to merge two arrays in a zipper like fashion in Bash?
问题描述
我试图以一种类似拉链的方式将两个数组合并为一个.我很难做到这一点.
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)
我曾尝试使用嵌套的 for 循环,但无法弄清楚.我不希望输出为 13572468,而是 12345678.
I have tried with nested for-loops but can't figure it out. I don't want the output to be 13572468 but 12345678.
我正在编写的实际脚本在这里(http://ix.io/iZR).但它显然没有按预期工作.我要么打印整个 array2(例如 124683),要么只打印第一个索引,就像循环不起作用一样(例如 12325272).
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).
那么我如何获得输出:
one two three four five six seven eight
上面有两个数组?
我能够用两个 for 循环和 paste
(http://ix.io/iZU).看看是否有人有更好的解决方案仍然很有趣.所以如果你有时间,请看看.
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.
推荐答案
假设两个数组的大小相同,
Assuming both arrays are the same size,
unset result
for (( i=0; i<${#array1[*]}; ++i)); do
result+=( "${array1[$i]}" "${array2[$i]}" )
done
这篇关于如何在 Bash 中像时尚一样在拉链中合并两个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!