7

I have these files in a folder:

chap11-solutions.pdf
chap12-solutions.pdf
chap13-solutions.pdf
chap14-solutions.pdf
chap15-solutions.pdf
chap16-solutions.pdf
chap17-solutions.pdf
chap21-solutions.pdf
chap22-solutions.pdf
chap23-solutions.pdf
chap24-solutions.pdf
chap25-solutions.pdf
chap26-solutions.pdf
chap2-solutions.pdf
chap3-solutions.pdf
chap4-solutions.pdf
chap5-solutions.pdf
chap6-solutions.pdf
chap7-solutions.pdf
chap8-solutions.pdf
chap9-solutions.pdf

how do I sort them in this way: chap1..., chap...2, ...., chap11..., chap12,... using Ubuntu bash shell? Thanks.

4 Answers 4

25
ls|sort -V

The -V parameter ensures that chap10 is considered upper that chap9.

Sign up to request clarification or add additional context in comments.

2 Comments

Just be aware that the -V option works only for relatively new GNU coreutils - it doesn't work for 5.93 (the one that's shipped by default with Mac OS 10.6).
OP uses Ubuntu, so he likely have a recent GNU coreutils :)
9

GNU ls has a version sort built-in:

ls -lv

1 Comment

thanks for this new very useful info, I never know this old tool got that handful switch. :D
2

If you have ruby(1.9.1+)

ruby -e 'puts Dir["chap*pdf"].sort_by{|x|x[/\d+/].to_i}'

1 Comment

One more nice thing about Ruby. Thanks for the info. Good luck in so.com. :D
1

Assuming that you want to rename the files so you don't have to keep sorting them later:

for f in chap*-solutions.pdf; do num=`echo $f | grep -o "[0123456789]\+"`; two_num=`printf "%02d" $num`; mv $f chap$two_num-solutions.pdf; done
  • grep -o "[0123456789]+" outputs the chapter number (one or two digits)
  • printf returns a string that contains the zero-padded number

1 Comment

And this is what they call "thoughtful". It touched my intention of renaming some files. Thanks a lot :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.