按数字顺序对目录中的文件进行排序和列出 [英] Sort and list the files from a directory in numeric order
问题描述
这是我的文件夹结构.
/home/files/encounters 9-22-11-0.jpg ../home/files/encounters 9-22-11- [n] .jpg
/home/files/encounters 9-22-11-0.jpg .. /home/files/encounters 9-22-11-[n].jpg
puts Dir.glob("/home/files/*.jpg")[0]
当我执行上述代码时,它显示了第六个文件(索引5 =>/home/files/encounters 9-22-11-5.jpg),但实际上我需要将输出作为第一个文件(索引0 = >/home/files/encounters 9-22-11-0.jpg)
When i execute the above code, it displayed the sixth file (index 5 => /home/files/encounters 9-22-11-5.jpg), but actually i need the output as first file(index 0 => /home/files/encounters 9-22-11-0.jpg)
如何按照用户定义的排序顺序对文件进行排序?喜欢
How can i sort the files as user defined sorting order?. like
当我尝试..
.. [0] =>/home/files/encounters 9-22-11-5.jpg
.. [1] =>/home/files/encounters 9-22-11-21.jpg
.. [2] =>/home/files/encounters 9-22-11-39.jpg
When i tried..
..[0] => /home/files/encounters 9-22-11-5.jpg
..[1] => /home/files/encounters 9-22-11-21.jpg
..[2] => /home/files/encounters 9-22-11-39.jpg
但是,我需要
.. [0] =>/home/files/encounters 9-22-11-0.jpg
.. [1] =>/home/files/encounters 9-22-11-1.jpg
.. [2] =>/home/files/encounters 9-22-11-2.jpg
But, I need
..[0] => /home/files/encounters 9-22-11-0.jpg
..[1] => /home/files/encounters 9-22-11-1.jpg
..[2] => /home/files/encounters 9-22-11-2.jpg
其他信息,排序也不起作用.
Additional information, sorting is also not working.
f = Dir.glob("/home/files/*.jpg").sort
f [0] =>/home/files/encounters 9-22-11-0.jpg
f [0] =>/home/files/encounters 9-22-11-1.jpg
f [0] =>/home/files/encounters 9-22-11-10.jpg
f [0] =>/home/files/encounters 9-22-11-11.jpg
f = Dir.glob("/home/files/*.jpg").sort
f[0] => /home/files/encounters 9-22-11-0.jpg
f[0] => /home/files/encounters 9-22-11-1.jpg
f[0] => /home/files/encounters 9-22-11-10.jpg
f[0] => /home/files/encounters 9-22-11-11.jpg
推荐答案
puts Dir.glob("/home/files/*.jpg").sort
如果您使用的格式是11-09-22-05.jpg
而不是9-22-11-5.jpg
,则可以工作.您可以尝试将它们排序为数字.
Would work if you had a format like 11-09-22-05.jpg
instead of 9-22-11-5.jpg
. You could try to sort them as a number instead.
Dir.glob("/home/files/*.jpg").sort_by {|s| s.gsub("-","").to_i }
但是似乎您有month-day-year-number,所以我想正确的排序方式要复杂得多.
But as it seems you have month-day-year-number I guess that the correct way to sort is a bit more complicated than that.
arr=%w[9-22-12-33.jpg 9-22-11-5.jpg 9-22-10-99.jpg 12-24-11-1.jpg]
arr.sort_by do |s|
t = s.split("-").map(&:to_i)
[t[2], t[0], t[1], t[3]]
end
它的工作方式是将9-22-11-5.jpg
重新格式化为包含[11, 9, 22, 5]
的数组,然后对其进行排序.
It works by reformatting 9-22-11-5.jpg
to an array containing [11, 9, 22, 5]
and then sorts by that instead.
这篇关于按数字顺序对目录中的文件进行排序和列出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!