遍历每个都有一对值的数组,依次对每个对进行操作 [英] Iterating over arrays, each with a pair of values, to operate on each pair in turn

查看:56
本文介绍了遍历每个都有一对值的数组,依次对每个对进行操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经知道如何通过从一组数组的每个数组中获取一个变量来生成对,例如:

I already know how to generate pairs by taking one variable from each of a set of arrays, as such:

#!/bin/bash
dir1=(foo baz)  # Not ideal: Want inputs to be dir1=(foo bar); dir2=(baz bat) instead
dir2=(bar bat)
for i in "${!dir1[@]}"
do
  echo "Comparing ${dir1[i]} to ${dir2[i]}"
done

产生以下输出.

比较foo和bar
比较baz和bat

Comparing foo to bar
Comparing baz to bat


有没有办法在同一行上的 foo bar 和同一行上的 baz bat 进行此循环?如下.


Is there a way to do this loop with foo bar on the same line and baz bat on it's same line? As follows.

pair1=(foo bar)
pair2=(baz bat)
...
pairN=(qux quux)
...
do
  # then, inside the loop, compare the pair
done

推荐答案

您可以使用 $ {!prefix @} 遍历以 prefix 开头的变量名,然后 namerefs 指代以每个名称存储的内容:

You can use ${!prefix@} to iterate over variable names starting with prefix, and namerefs to refer to content stored under each name:

#!/usr/bin/env bash
case $BASH_VERSION in ''|[123].*|4.[012].*) echo "ERROR: Bash 4.3 required" >&2; exit 1;; esac

pair1=(foo bar)
pair2=(baz bat)
pairN=(qux quux)

declare -n currPair
for currPair in "${!pair@}"; do
  echo "Comparing ${currPair[0]} to ${currPair[1]}"
done

https://ideone.com/pTehPZ

这篇关于遍历每个都有一对值的数组,依次对每个对进行操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆