【问题标题】:Bash iterate through multiple arraysBash 遍历多个数组
【发布时间】:2013-07-26 20:56:56
【问题描述】:

我已经定义了多个数组:

array1=(el1 el2 el3 el4 el5)
array2=(el10 el12 el14)
array3=(el5 el4 el11 el8)

我需要遍历所有数组的所有元素。以下是我使用的语法:

for j in {1..3}
do
    for (( k = 0 ; k < ${#array$j[*]} ; k++ ))
    do
        #perform actions on array elements, refer to array elements as "${array$j[$k]}"
    done
done

但是,上面的 sn-p 失败并显示消息

k < ${#array$j[*]} : bad substitution and 
${array$j[$k]}: bad substitution

我的数组语法有什么问题?

【问题讨论】:

  • 你真的需要$j$k,还是直接写for value in "${array1[@]}" "${array2[@]}" "${array3[@]}" ; do ... ; done
  • 不幸的是,我知道。数组的实际数量是 11,每个数组中元素的操作需要不同。
  • 你的数组赋值语法错误,不应该有逗号。
  • 道歉 - 这只是我写问题时的一个错字。我的脚本中的数组规范没有任何逗号。

标签: arrays bash loops


【解决方案1】:

您的脚本不正确。

  1. 首先,不应使用逗号分隔 3 个数组中的各个元素。
  2. 然后要使用数组名称作为变量,您需要使用间接方式

以下应该可以工作:

array1=(el1 el2 el3 el4 el5)
array2=(el10 el12 el14)
array3=(el5 el4 el11 el8)

for j in {1..3}
do
    n="array$j[@]"
    arr=("${!n}")
    for (( k = 0 ; k < ${#arr[@]} ; k++ ))
    do
        #perform actions on array elements, refer to array elements as "${array$j[$k]}"
        echo "Processing: ${arr[$k]}"
    done
done

这将处理所有 3 个数组并给出以下输出:

Processing: el1
Processing: el2
Processing: el3
Processing: el4
Processing: el5
Processing: el10
Processing: el12
Processing: el14
Processing: el5
Processing: el4
Processing: el11
Processing: el8

【讨论】:

  • 哈,我们刚刚在十五秒内发布了相同的答案。伟大的思想 。 . . ! :-P
  • 哇,这真的很有趣,不能同意更多:)
  • 谢谢你 - 做到了。数组定义中的逗号只是我在写问题时犯的一个错字。我的脚本中的数组规范没有任何逗号。使用间接解决了这个问题。
  • 如果这个答案帮助您解决了问题,请考虑将其标记为“已接受”,以便以后遇到类似问题的用户能够轻松看到。
【解决方案2】:

这个:

array1=(el1 el2 el3 el4 el5)
array2=(el10 el12 el14)
array3=(el5 el4 el11 el8)

for j in {1..3} ; do
    # copy array$j to a new array called tmp_array:
    tmp_array_name="array$j[@]"
    tmp_array=("${!tmp_array_name}")

    # iterate over the keys of tmp_array:
    for k in "${!tmp_array[@]}" ; do
        echo "\${array$j[$k]} is ${tmp_array[k]}"
    done
done

打印这个:

${array1[0]} is el1
${array1[1]} is el2
${array1[2]} is el3
${array1[3]} is el4
${array1[4]} is el5
${array2[0]} is el10
${array2[1]} is el12
${array2[2]} is el14
${array3[0]} is el5
${array3[1]} is el4
${array3[2]} is el11
${array3[3]} is el8

可能有一些方法可以在不创建 tmp_array 的情况下执行此操作,但没有它我无法让间接工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-28
    • 1970-01-01
    • 2021-04-23
    • 2012-05-24
    相关资源
    最近更新 更多