Tim
Tim

Reputation: 99508

how to get desired order by expansion in bash

$ echo  {A,B}{1,2,3}.pdf
A1.pdf A2.pdf A3.pdf B1.pdf B2.pdf B3.pdf

How can I get the following output:

A1.pdf B1.pdf A2.pdf B2.pdf A3.pdf B3.pdf

Thanks.

Upvotes: 0

Views: 77

Answers (4)

rici
rici

Reputation: 241881

I suppose this is cheating, but it does give the desired output:

echo fdp.{3,2,1}{B,A} | rev

Upvotes: 4

jaypal singh
jaypal singh

Reputation: 77155

The result of brace expansion is not sorted and left to right order is preserved.

To achieve your desired output you can do the following but you can see how quickly it can get complicated.

$ echo {{A,B}1,{A,B}2,{A,B}3}.pdf
A1.pdf B1.pdf A2.pdf B2.pdf A3.pdf B3.pdf

Simple loop should be easy to scale and read:

$ for n in {1..3}; do list+=( {A..B}$n.pdf ); done; echo "${list[@]}"
A1.pdf B1.pdf A2.pdf B2.pdf A3.pdf B3.pdf

I have used an intermediate array to store expanded names. You may choose to print them as your encounter. I am assuming your intention is to do something with them once they are generated.

Upvotes: 3

Leo
Leo

Reputation: 3146

for n in 1 2 3; do for l in A B; do echo -n "$l$n.pdf "; done; done; echo

or

for n in {1..3}; do for l in {A..B}; do echo -n "$l$n.pdf "; done; done; echo

Upvotes: 1

Etan Reisner
Etan Reisner

Reputation: 81012

$ for n in 1 2 3; do printf '%s ' {A,B}"$n.pdf"; done; echo
A1.pdf B1.pdf A2.pdf B2.pdf A3.pdf B3.pdf

$ for n in 1 2 3; do echo -n {A,B}"$n.pdf "; done; echo
A1.pdf  B1.pdf A2.pdf  B2.pdf A3.pdf  B3.pdf

$ for n in 1 2 3; do echo -n {A,B}"$n.pdf"; echo -n " "; done; echo
A1.pdf B1.pdf A2.pdf B2.pdf A3.pdf B3.pdf

# One of the relatively rare times where not quoting a command substitution is useful.
$ echo $(printf %s\\n {A,B}{1,2,3}.pdf | sort -k1.2,1.2)
A1.pdf B1.pdf A2.pdf B2.pdf A3.pdf B3.pdf

# Same idea as above but with different all-on-one line mechanism.
$ printf %s\\n {A,B}{1,2,3}.pdf | sort -k1.2,1.2 | tr '\n' ' '; echo
A1.pdf B1.pdf A2.pdf B2.pdf A3.pdf B3.pdf

Upvotes: 1

Related Questions