在bash中遍历元组? [英] Loop over tuples in bash?

查看:225
本文介绍了在bash中遍历元组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在bash中遍历元组?

Is it possible to loop over tuples in bash?

作为一个例子,如果以下方法有效,那就太好了

As an example, it would be great if the following worked:

for (i,j) in ((c,3), (e,5)); do echo "$i and $j"; done

有没有一种解决方法,可以让我以某种方式遍历元组?

Is there a workaround that somehow lets me loop over tuples?

推荐答案

$ for i in c,3 e,5; do IFS=","; set -- $i; echo $1 and $2; done
c and 3
e and 5

关于set的这种用法(来自man builtins):

About this use of set (from man builtins):

在选项处理之后剩余的任何参数都被视为值 位置参数,并依次分配给$ 1,$ 2, ... $ n

Any arguments remaining after option processing are treated as values for the positional parameters and are assigned, in order, to $1, $2, ... $n

IFS=","设置字段分隔符,以便将每个$i正确地分割为$1$2.

The IFS="," sets the field separator so every $i gets segmented into $1 and $2 correctly.

通过此博客.

更正确的版本,如@SLACEDIAMOND建议:

more correct version, as suggested by @SLACEDIAMOND:

$ OLDIFS=$IFS; IFS=','; for i in c,3 e,5; do set -- $i; echo $1 and $2; done; IFS=$OLDIFS
c and 3
e and 5

这篇关于在bash中遍历元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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