6 # Renames all the files in a directory with the given file extension.
7 # The renamed files will just have numbers.
22 $fu_args = { :verbose => true }
24 # Fill in $opts values
25 parser = OptionParser.new do |myparser|
26 myparser.banner = "Usage: #{ File.basename($0) } [opts]"
27 myparser.separator("Specific options:")
28 myparser.on("--num-digits DIGITS", "-D",
29 "Set the number of digits in the numbering scheme.") do |d|
30 opts.num_digits = d.to_i
32 myparser.on("--dry-run", "-d",
33 "Show what would be done, without doing it.") do |d|
34 $fu_args = { :verbose => true, :noop => true }
37 myparser.on("--file-extension EXTENSION", "-e",
38 "The file extension for the files to rename.") do |e|
44 raise "invalid num_digits: #{opts.num_digits}" unless
46 raise "must give an extension" unless opts.extension != nil
58 #.#{$opts.extension}").sort.each do |f|
60 Dir.glob("*.#{$opts.extension}").sort.each do |f|
66 $total_files = $total_files + 1
69 def get_file_name(num)
70 return sprintf("%0#{$opts.num_digits}d.#{$opts.extension}", num)
73 def rename_files(file)
74 FileUtils.mv(file, get_file_name(1 + $total_files), $fu_args)
75 $total_files = $total_files + 1
80 $opts = MyOptions.parse(ARGV)
81 rescue Exception => msg
82 $stderr.print("#{msg}.\nType --help to see usage information.\n")
86 # make sure there aren't too many files
88 max_total_files = pow(10, $opts.num_digits) - 1
89 file_iter { |f| count_files(f) }
90 if ($total_files > max_total_files) then
91 raise "With #{$opts.num_digits} digit(s), we can only have at most \
92 #{max_total_files} files-- but there are #{$total_files} files in the \
93 #directory. Try setting a higher value for num_digits, using -D."
98 file_iter { |f| rename_files(f) }