How to sort files in a folder using bash?

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 can I sort them as follows: chap1 ..., chap ... 2, ...., chap11 ..., chap12, ... using the Ubuntu bash shell? Thank.

+5
source share
4 answers
ls|sort -V

The parameter -Vguarantees that it chap10is considered upper than chap9.

+22
source

GNU lshas a built-in version:

ls -lv
+8
source

(1.9.1 +)

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

, , :

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]+" ( )
  • printf ,
+1

All Articles