【问题标题】:Make relation between two different arrays in a loop [duplicate]在循环中建立两个不同数组之间的关系[重复]
【发布时间】:2019-07-07 13:12:54
【问题描述】:

我创建了两个数组:

第一个数组:

echo "${array1[@]}"
two
three
four
five

第二个数组:

echo "${array2[@]}"
apples
carrots
potatoes
tomatoes

我想将它们组合在一个循环中(或类似的东西),并保持第一个数组和第二个数组之间的关系。

two apples
three carrots
four potatoes
five tomatoes

谢谢。

【问题讨论】:

    标签: arrays bash loops multidimensional-array indexing


    【解决方案1】:

    要压缩两个并行数组,请遍历索引。 (这假设两个数组使用相同的索引,几乎总是如此。)

    for i in "${!array1[@]}"; do
      new_array+=( "${array1[i]} ${array2[i]}" )
    done
    

    【讨论】:

    • 非常感谢 chepner 这很好用!
    猜你喜欢
    • 1970-01-01
    • 2020-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-08
    • 1970-01-01
    相关资源
    最近更新 更多