击合并两个数组 [英] Bash combine two arrays

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

问题描述

我有以下的情况,两个数组,我们姑且称之为A(0 1),B(1 2),我需要他们在一个新的数组C(0组合:1 0:2 1:1 1:2 ),最新的i位已经出来是这样的循环:

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 )

推荐答案

由于猛砸支持稀疏数组,这是更好地遍历数组比以上尺寸的基础上使用索引。

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")'

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

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