Agefiles

From EggeWiki

Jump to: navigation, search

My script to delete old files

#!/bin/env ruby
 
require 'find'
require 'optparse'
 
dryrun = false
 
args = OptionParser.new do |opts|
  opts.banner = "Usage: #{$0} [options] directory [size]"
 
  opts.on("-n", "--dry-run", "show what would have been deleted") do |v|
    dryrun = true
  end
end.parse!
 
DIR = args[0] || '.'
File.directory?(DIR) || raise("#{DIR} is not a directory")
MAXSIZE = case args[1]
when nil
  1000000
when /([0-9]+)[Kk]B?/
  $1.to_i * 1024
when /([0-9]+)[mM]B?/
  $1.to_i * 1024 * 1024
when /([0-9]+)[gG]B?/
  $1.to_i * 1024 * 1024 * 1024
else
  $1.to_i
end
 
 
files = []
total = 0
Find.find(DIR) do |f|
  if File.file?(f) then
    files << [ File.mtime(f), File.size(f), f ]
    total += File.size(f)
  end
end
 
files = files.sort_by { |x| x[0] }
 
puts "#{DIR} is currently size #{total} and needs to be no more than #{MAXSIZE}"
fcount=0
bcount=0
while total > MAXSIZE && (item = files.shift) do
  total -= item[1]
  bcount += item[1]
  if dryrun then
    puts "unlink #{item[2]}"
  else
    File.unlink(item[2])
  end
  fcount += 1
end
 
puts "deleted #{fcount} files totalling #{bcount} bytes"
Personal tools
Travelling Salesman

Get the app!