在bash中遍历元组? [英] Loop over tuples in 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屋!