如何在Bash中以类似拉链的方式合并两个数组? [英] How to merge two arrays in a zipper like fashion in Bash?

查看:124
本文介绍了如何在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆