Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort and list the files from a directory in numeric order

This is my folder structure.

/home/files/encounters 9-22-11-0.jpg .. /home/files/encounters 9-22-11-[n].jpg

puts Dir.glob("/home/files/*.jpg")[0] 

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

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

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

like image 517
Mr. Black Avatar asked Oct 19 '11 10:10

Mr. Black


People also ask

How do I sort numerical order in Linux?

How to sort by number. To sort by number pass the -n option to sort . This will sort from lowest number to highest number and write the result to standard output. Suppose a file exists with a list of items of clothing that has a number at the start of the line and needs to be sorted numerically.

Which command is used to sort the numeric file?

The sort command sorts the contents of a file, in numeric or alphabetic order, and prints the results to standard output (usually the terminal screen).


1 Answers

puts Dir.glob("/home/files/*.jpg").sort

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 }

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

It works by reformatting 9-22-11-5.jpg to an array containing [11, 9, 22, 5] and then sorts by that instead.

like image 126
Jonas Elfström Avatar answered Sep 28 '22 04:09

Jonas Elfström