I’ve been trying to write a Ruby script to find and delete the oldest AVI file in a folder. I found a script in Python that is very close, and I got a good start on the Ruby solution myself with:
require 'fileutils'
stat = Sys::Filesystem.stat("/")
mb_available = stat.block_size * stat.blocks_available / 1024 / 1024
#if there is less than 130MB free
if mb_available < 130000
require 'find'
movie_file_paths = []
#grab all the files in the folder
Find.find('/Users/jody/Movies') do |path|
movie_file_paths << path if /.*\.avi/.match(path) != nil
end
end
But, I’m having a tough time with the rest. Any help would be appreciated!
EDIT:
This was the solution:
movie_file_paths = []
Dir.glob("/Users/jody/Movies/**/*.avi").each { |file| movie_file_paths << file if File.file? file }
movie_file_paths.sort_by {|f| File.mtime(f)}
deleteme = movie_file_paths.first
Use
File.mtime(filename)to get the last modified time of the file.movie_file_path.sort_by {|f| File.mtime(f)}will return a sorted array bymtime. You can then delete the file usingFile.delete(filename).Edit: Last accessed time
atimemight be a better option thanmtime.