在bash中同时迭代两个数组 [英] Iterate over two arrays simultaneously in bash
问题描述
我有两个数组.
array=(
Vietnam
Germany
Argentina
)
array2=(
Asia
Europe
America
)
我想同时循环遍历这两个数组,即对两个数组的第一个元素调用命令,然后对第二个元素调用相同的命令,依此类推.伪代码:
I want to loop over these two arrays simulataneously, i.e. invoke a command on the first elements of the two arrays, then invoke the same command on the second elements, and so on. Pseudocode:
for c in ${array[*]}
do
echo -e " $c is in ......"
done
我该怎么做?
推荐答案
根据 anishsane 的回答和其中的评论,我们现在知道您想要什么.这是 bashier 风格的相同内容,使用 for 循环.请参阅参考中的循环结构部分手册.我也在使用 printf
而不是 echo
.
From anishsane's answer and the comments therein we now know what you want. Here's the same thing in a bashier style, using a for loop. See the Looping Constructs section in the reference manual. I'm also using printf
instead of echo
.
#!/bin/bash
array=( "Vietnam" "Germany" "Argentina" )
array2=( "Asia" "Europe" "America" )
for i in "${!array[@]}"; do
printf "%s is in %s\n" "${array[i]}" "${array2[i]}"
done
另一种可能性是使用关联数组:
Another possibility would be to use an associative array:
#!/bin/bash
declare -A continent
continent[Vietnam]=Asia
continent[Germany]=Europe
continent[Argentina]=America
for c in "${!continent[@]}"; do
printf "%s is in %s\n" "$c" "${continent[$c]}"
done
根据您想要做什么,您不妨考虑第二种可能性.但请注意,您不会轻易控制在第二种可能性中字段显示的顺序(好吧,它是一个关联数组,所以这并不奇怪).
Depending on what you want to do, you might as well consider this second possibility. But note that you won't easily have control on the order the fields are shown in the second possibility (well, it's an associative array, so it's not really a surprise).
这篇关于在bash中同时迭代两个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!