bash 中数组的内联扩展
Inline expansion of arrays in bash
我正在尝试扩展 bash 中的数组:
FILES=(2009q{1..4})
echo ${FILES[@]}
echo ${FILES[@]}.zip
输出为:
2009q1 2009q2 2009q3 2009q4
2009q1 2009q2 2009q3 2009q4.zip
但是我怎样才能像 echo 2009q{1..4}.zip
那样扩展最后一行,使最后一行看起来像:
2009q1.zip 2009q2.zip 2009q3.zip 2009q4.zip
...但使用数组 FILES
?
您可以使用 printf
:
printf "%s.zip " "${FILES[@]}"
2009q1.zip 2009q2.zip 2009q3.zip 2009q4.zip
FILES=(2009q{1..4})
echo ${FILES[@]/%/.zip}
输出:
2009q1.zip 2009q2.zip 2009q3.zip 2009q4.zip
来自 Bash 的 Parameter Expansion:
${parameter/pattern/string}
: The pattern is expanded to produce a pattern just as in filename expansion. Parameter is expanded and the longest match of pattern against its value is replaced with string. If pattern begins with '/', all matches of pattern are replaced with string. Normally only the first match is replaced. If pattern begins with '#', it must match at the beginning of the expanded value of parameter. If pattern begins with '%', it must match at the end of the expanded value of parameter. If string is null, matches of pattern are deleted and the / following pattern may be omitted. If parameter is '@' or '', the substitution operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with '@' or '', the substitution operation is applied to each member of the array in turn, and the expansion is the resultant list.
我正在尝试扩展 bash 中的数组:
FILES=(2009q{1..4})
echo ${FILES[@]}
echo ${FILES[@]}.zip
输出为:
2009q1 2009q2 2009q3 2009q4
2009q1 2009q2 2009q3 2009q4.zip
但是我怎样才能像 echo 2009q{1..4}.zip
那样扩展最后一行,使最后一行看起来像:
2009q1.zip 2009q2.zip 2009q3.zip 2009q4.zip
...但使用数组 FILES
?
您可以使用 printf
:
printf "%s.zip " "${FILES[@]}"
2009q1.zip 2009q2.zip 2009q3.zip 2009q4.zip
FILES=(2009q{1..4})
echo ${FILES[@]/%/.zip}
输出:
2009q1.zip 2009q2.zip 2009q3.zip 2009q4.zip
来自 Bash 的 Parameter Expansion:
${parameter/pattern/string}
: The pattern is expanded to produce a pattern just as in filename expansion. Parameter is expanded and the longest match of pattern against its value is replaced with string. If pattern begins with '/', all matches of pattern are replaced with string. Normally only the first match is replaced. If pattern begins with '#', it must match at the beginning of the expanded value of parameter. If pattern begins with '%', it must match at the end of the expanded value of parameter. If string is null, matches of pattern are deleted and the / following pattern may be omitted. If parameter is '@' or '', the substitution operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with '@' or '', the substitution operation is applied to each member of the array in turn, and the expansion is the resultant list.