开发者

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-solut开发者_C百科ions.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.


ls|sort -V

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


GNU ls has a version sort built-in:

ls -lv


If you have ruby(1.9.1+)

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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜