在Bash中合并两个数组 [英] Merging two arrays in Bash

查看:84
本文介绍了在Bash中合并两个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下情况,两个数组,我们称它们为A(0 1)和B(1 2),我需要将它们组合成一个新的数组C(0:1 0:2 1:1 1:2 ),我想出的最新一点就是这个循环:

I have the following situation, two arrays, let's call them A( 0 1 ) and B ( 1 2 ), i need to combine them in a new array C ( 0:1 0:2 1:1 1:2 ), the latest bit i've come up with is this loop:

   for ((z = 0; z <= ${#A[@]}; z++)); do
     for ((y = 0; y <= ${#B[@]}; y++)); do
       C[$y + $z]="${A[$z]}:"
       C[$y + $z + 1]="${B[$y]}"
     done
   done

但是它不能很好地工作,因为我得到的输出是这样的:

But it doesn't work that well, as the output i get this:

 0: : : :

在这种情况下,输出应为0:1 0:2,因为A =(0)和B =(1 2)

In this case the output should be 0:1 0:2 as A = ( 0 ) and B = ( 1 2 )

推荐答案

由于Bash支持稀疏数组,因此遍历数组要比使用基于大小的索引更好.

Since Bash supports sparse arrays, it's better to iterate over the array than to use an index based on the size.

a=(0 1); b=(2 3)
i=0
for z in ${a[@]}
do
    for y in ${b[@]}
    do
        c[i++]="$z:$y"
    done
done
declare -p c   # dump the array

输出:

declare -a c='([0]="0:2" [1]="0:3" [2]="1:2" [3]="1:3")'

这篇关于在Bash中合并两个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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