zsh 数组元素如何在单个扩展中进行转换?
How can zsh array elements be transformed in a single expansion?
假设你有一个像这样的 zsh 数组:
a=("x y" "v w")
我想取每个元素的第一个字,比如:
b=()
for e in $a; {
b=($b $e[(w)0])
}
所以现在我在 b:
中有了我需要的东西
$ print ${(qq)b}
'x' 'v'
有没有办法在单个扩展表达式中做到这一点? (即不需要 for 循环来处理每个数组元素并将结果累积到新数组中)。
可以通过从第一次出现的白色 space 移除数组的每个元素的末尾来获取单词,如下所示:
$ print ${(qq)a%% *}
'x' 'v'
值得注意的是,%%
表达式(和其他一些表达式)可用于数组元素:
In the following expressions, when name is an array and the substitution is not quoted, or if the ‘(@)
’ flag or the name[@]
syntax is used, matching and replacement is performed on each array element separately.
...
${name%pattern}
${name%%pattern}
If the pattern matches the end of the value of name, then substitute the value of name with the matched portion deleted; otherwise, just substitute the value of name. In the first form, the smallest matching pattern is preferred; in the second form, the largest matching pattern is preferred.
假设你有一个像这样的 zsh 数组:
a=("x y" "v w")
我想取每个元素的第一个字,比如:
b=()
for e in $a; {
b=($b $e[(w)0])
}
所以现在我在 b:
中有了我需要的东西$ print ${(qq)b}
'x' 'v'
有没有办法在单个扩展表达式中做到这一点? (即不需要 for 循环来处理每个数组元素并将结果累积到新数组中)。
可以通过从第一次出现的白色 space 移除数组的每个元素的末尾来获取单词,如下所示:
$ print ${(qq)a%% *}
'x' 'v'
值得注意的是,%%
表达式(和其他一些表达式)可用于数组元素:
In the following expressions, when name is an array and the substitution is not quoted, or if the ‘
(@)
’ flag or thename[@]
syntax is used, matching and replacement is performed on each array element separately.
...
${name%pattern}
${name%%pattern}
If the pattern matches the end of the value of name, then substitute the value of name with the matched portion deleted; otherwise, just substitute the value of name. In the first form, the smallest matching pattern is preferred; in the second form, the largest matching pattern is preferred.