Reputation: 817
How would I sort a directory into files created before and after any given time and date?
I need to make two lists, one of files before, and the other of files after, a certain date/time.
Upvotes: 1
Views: 1862
Reputation: 1053
Dir["dir_path/*"].sort_by { |p| File::Stat.new(p).birthtime }
works on macos
Upvotes: 2
Reputation: 1287
The creation time with Ruby on OS X is not available through the File API. One way is shelling out to stat(1)
. Not pretty but does at least return the creation (a.k.a birth) time:
def birth(file)
Time.at(`stat -f%B "#{file}"`.chomp.to_i)
end
Dir.entries('.').sort_by {|f| birth f }
Or use the partition answer given.
Here's a detailed post on a common misconception: ctime does not mean creation time.
Upvotes: 3
Reputation: 114218
You can use Enumerable#partition
:
files = Dir.entries('.')
time = Time.parse("2013-09-01")
before, after = files.partition { |file| File.ctime(file) < time }
As the Tin Man noted, ctime
is not the only file time method. Maybe atime
or mtime
is a better choice.
Upvotes: 1
Reputation: 744
Here's my answer. You can sort the files in a directory by their modified time with something along these lines using File.new('filename').mtime
files_hash = Hash.new
Dir.foreach('.') do |file_name|
modified_time = File.new(file_name).mtime
unless file_name == '.' || file_name == '..' then
files_hash[file_name] = modified_time
end
end
# Sort the hash.
files_hash = files_hash.sort_by {|key, value| value}
files_hash.each do |name, time|
puts "#{name} was modified at #{time}"
end
Upvotes: 0
Reputation: 7225
ctime
Returns the change time for stat (that is, the time directory information about the file was changed, not the file itself).
Note that on Windows (NTFS), returns creation time (birth time).
http://www.ruby-doc.org/core-2.0.0/File/Stat.html#method-i-ctime
so you can do something like this.
Dir.entries('.').sort {|a,b| File.stat(a).ctime <=> File.stat(b).ctime}
Upvotes: 0