4

假设我在 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
4

1 回答 1

6

您需要设置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.
于 2014-10-23T23:30:55.440 回答