如何在zsh中扩展数组的元素?

时间:2014-10-23 22:52:43

标签: arrays zsh variable-expansion

假设我在zsh中有一个数组

a=(1 2 3)

我想将.txt追加到每个元素

echo ${a}.txt # this doesn't work

所以输出是

1.txt 2.txt 3.txt

更新:

我想我可以做到这一点,但我认为这是一种更惯用的方式:

for i in $a; do
    echo $i.txt
done

1 个答案:

答案 0 :(得分:3)

您需要设置RC_EXPAND_PARAM选项:

$ setopt RC_EXPAND_PARAM
$ echo ${a}.txt
1.txt 2.txt 3.txt

来自zsh手册:

RC_EXPAND_PARAM (-P)
              Array  expansions of the form `foo${xx}bar', where the parameter xx is set to
              (a b c), are substituted  with  `fooabar  foobbar  foocbar'  instead  of  the
              default  `fooa  b  cbar'.   Note that an empty array will therefore cause all
              arguments to be removed.

您也可以使用^标志设置此选项仅用于一个数组扩展:

$ echo ${^a}.txt
1.txt 2.txt 3.txt
$ echo ${^^a}.txt
1 2 3.txt

再次引用zsh手册:

${^spec}
              Turn on the RC_EXPAND_PARAM option for the evaluation of spec; if the `^'  is
              doubled,  turn it off.  When this option is set, array expansions of the form
              foo${xx}bar, where the parameter xx is set to (a b c), are  substituted  with
              `fooabar foobbar foocbar' instead of the default `fooa b cbar'.  Note that an
              empty array will therefore cause all arguments to be removed.