Skip to content

Instantly share code, notes, and snippets.

@Slackwise
Last active October 19, 2015 20:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Slackwise/b2885d55737cda45011a to your computer and use it in GitHub Desktop.
Save Slackwise/b2885d55737cda45011a to your computer and use it in GitHub Desktop.
Delete all files matching a regex in a directory of directories.
require 'date'
require 'fileutils'
require 'pathname'
EBS_EMAIL_DIR = Pathname('\\\\millmed\\shared\\EBS_Email\\')
REGEX = /^(\d\d\d\d-\d\d-\d\d) \d{4} Batch Charged \[ORG \d{1,3} Location \d{1,3} - Batch \d{6}\]\.txt$/
CUTOFF_DATE = Date.today - 180
MAX_FILES_TO_DELETE_PER_INTERVAL = 100
MAX_TIME_TO_WAIT_PER_INTERVAL = 30 # Seconds
$DONT_HOSE_SYSTEM_COUNTER = 0
def pause_if_system_hosed
if $DONT_HOSE_SYSTEM_COUNTER < MAX_FILES_TO_DELETE_PER_INTERVAL
$DONT_HOSE_SYSTEM_COUNTER += 1
else
puts "Taking a break..."
sleep(MAX_TIME_TO_WAIT_PER_INTERVAL)
$DONT_HOSE_SYSTEM_COUNTER = 0
end
end
def parse_date(file_pathname)
match = file_pathname.basename.to_s.match(REGEX)
if match && (match.length == 2) && match[1]
Date.parse(match[1])
end
end
def delete_matching_file(file_pathname)
date = parse_date(file_pathname)
if date && (date < CUTOFF_DATE)
puts file_pathname.basename
file_pathname.delete
pause_if_system_hosed
end
rescue
puts "Failed to delete #{file_pathname}:\n#$!"
exit 1 # Need to review what happened and why.
end
def delete_matches_in_dir(dir)
dir.each_child do |child|
if child.directory?
delete_matches_in_dir(child) # We must go deeper!
else
delete_matching_file(child)
end
end
end
begin
delete_matches_in_dir(EBS_EMAIL_DIR)
rescue
puts "Fatal Error: #$!:"
exit 1
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment