假设我在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
答案 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.