在 bash 中同时迭代两个数组

我有两个数组。

array=(
Vietnam
Germany
Argentina
)
array2=(
Asia
Europe
America
)

我想同时在这两个数组上循环,即对两个数组的第一个元素调用命令,然后对第二个元素调用相同的命令,依此类推。伪代码:

for c in ${array[*]}
do
echo -e " $c is in ......"
done

我怎么能这么做?

97125 次浏览

您需要在 array & array2上进行循环

i=0
while [ $i -lt ${#array[*]} ]; do
echo ${array[$i]} is in ${array2[$i]}
i=$(( $i + 1));
done


Vietnam is in Asia
Germany is in Europe
Argentina is in America

EDIT: Do not use the below tr based implementation. It will not work for array elements containing spaces. Not removing it so as to keep the comments relevant. See glenn jackman's comment instead of below answer.

编辑

Alternately, you can use this option (without loop):

paste <(tr ' ' '\n' <<< ${array[*]}) <(tr ' ' '\n' <<< ${array2[*]}) | sed 's/\t/ is in /'

From anishsane's answer and the comments therein we now know what you want. Here's the same thing in a 巴希尔 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

另一种可能性是使用关联数组:

#!/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

根据您想要做的事情,您不妨考虑第二种可能性。但是请注意,你不能轻易控制第二种可能性中字段显示的顺序(好吧,这是一个关联数组,所以这并不是一个真正的惊喜)。

如果所有数组的顺序都正确,只需传递索引即可。

array=(
Vietnam
Germany
Argentina
)
array2=(
Asia
Europe
America
)


for index in ${!array[*]}; do
echo "${array[$index]} is in ${array2[$index]}"
done


Vietnam is in Asia
Germany is in Europe
Argentina is in America

如果两个 var 是具有多行的两个字符串,如下所示:

listA=$(echo -e "Vietnam\nGermany\nArgentina")
listB=$(echo -e "Asia\nEurope\nAmerica")

那么,这种情况的解决方案是:

while read strA <&3 && read strB <&4; do
echo "$strA is in $strB"
done 3<<<"$listA" 4<<<"$listB"

特别是针对提出的问题(包含3个项目的数组) :

for i in $(seq 0 2) ; do
echo "${array1[$i]} is in ${array2[$i]}"
done