简体   繁体   中英

Inline expansion of arrays in bash

I'm trying to expand an array in bash:

FILES=(2009q{1..4})
echo ${FILES[@]}
echo ${FILES[@]}.zip

Output is:

2009q1 2009q2 2009q3 2009q4
2009q1 2009q2 2009q3 2009q4.zip

But how can I expand the last line as in echo 2009q{1..4}.zip expansion, so that the last line looked like:

2009q1.zip 2009q2.zip 2009q3.zip 2009q4.zip

... but using array FILES ?

FILES=(2009q{1..4})
echo ${FILES[@]/%/.zip}

Output:

2009q1.zip 2009q2.zip 2009q3.zip 2009q4.zip

From Bash's 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.

You can use printf :

printf "%s.zip " "${FILES[@]}"

2009q1.zip 2009q2.zip 2009q3.zip 2009q4.zip

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM