Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - How to remove all files in a directory older than X days?

I have a directory of csv files called reports

I want to delete all files from the reports folder that are older than X number of days.

This works great to remove ALL files:

FileUtils.rm_rf("reports/.", secure: true)

But I want the filter of only remove files older than X number of days.

How?

like image 857
ToddT Avatar asked Sep 06 '25 03:09

ToddT


1 Answers

You can list all file names, then use File.stat to check the modification time of each file and remove each one of them.

For instance, you could use the following code:

# will count X days older than "reference_time"
reference_time = Time.now

# use the following value to delete files older than 30 days
delete_older_than = 30 * (24 * 3600) # value in seconds

all_files = Dir['reports/*']
all_files.each do |relative_file_name|
  # not really necessary, but I like to work with full file paths
  file_path = File.expand_path(relative_file_name)

  # if you want to be strict and delete only files (e.g. not folders),
  # this line skips any non-files.
  next unless File.file?(file_path)

  st = File.stat(file_path)  
  # modification time is at st.mtime

  if st.mtime < (reference_time - delete_older_than)
    File.unlink(file_path)
  end
end
like image 65
André Diego Piske Avatar answered Sep 08 '25 00:09

André Diego Piske