How to sort files in a folder using bash?
13,480
Solution 1
ls|sort -V
The -V
parameter ensures that chap10
is considered upper that chap9
.
Solution 2
GNU ls
has a version sort built-in:
ls -lv
Solution 3
If you have ruby(1.9.1+)
ruby -e 'puts Dir["chap*pdf"].sort_by{|x|x[/\d+/].to_i}'
Solution 4
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
Author by
wakandan
Updated on June 23, 2022Comments
-
wakandan almost 2 years
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.
-
Tomasz Elendt over 13 yearsJust 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). -
Arnaud Le Blanc over 13 yearsOP uses Ubuntu, so he likely have a recent GNU coreutils :)
-
wakandan over 13 yearsthanks for this new very useful info, I never know this old tool got that handful switch. :D
-
wakandan over 13 yearsAnd this is what they call "thoughtful". It touched my intention of renaming some files. Thanks a lot :D
-
wakandan over 13 yearsOne more nice thing about Ruby. Thanks for the info. Good luck in so.com. :D