问题描述
我有两个数组。
array=(
Vietnam
Germany
Argentina
)
array2=(
Asia
Europe
America
)
欲循环这两个数组以上simulataneously,即,在两个数组的第一元素调用命令,则在第二元件调用相同的命令,等等。伪code:
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
我怎样才能做到这一点?
How can i do this?
推荐答案
从anishsane的回答和意见在其中,我们现在知道你想要什么。这里有一个的 bashier 的风格同样的事情,使用for循环。请参阅部分。我还使用的printf
而不是回声
。
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=0;i<${#array[@]};++i)); 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!