Linux 如何使用bash对文件夹中的文件进行排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4773948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to sort files in a folder using bash?
提问by wakandan
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.
我如何以这种方式对它们进行排序: chap1..., chap...2, ...., chap11..., chap12,... 使用 Ubuntu bash shell?谢谢。
采纳答案by Arnaud Le Blanc
ls|sort -V
The -V
parameter ensures that chap10
is considered upper that chap9
.
该-V
参数确保chap10
被认为高于chap9
。
回答by mpenkov
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
grep -o "[0123456789]+"
输出章节编号(一位或两位数字)printf
返回一个包含零填充数字的字符串
回答by kurumi
If you have ruby(1.9.1+)
如果你有红宝石(1.9.1+)
ruby -e 'puts Dir["chap*pdf"].sort_by{|x|x[/\d+/].to_i}'
回答by Paused until further notice.
GNU ls
has a version sort built-in:
GNUls
有一个内置的版本排序:
ls -lv