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 }
23 opts.preserve_names = false
25 # Fill in $opts values
26 parser = OptionParser.new do |myparser|
27 myparser.banner = "Usage: #{ File.basename($0) } [opts]"
28 myparser.separator("Specific options:")
29 myparser.on("--num-digits DIGITS", "-D",
30 "Set the number of digits in the numbering scheme.") do |d|
31 opts.num_digits = d.to_i
33 myparser.on("--dry-run", "-d",
34 "Show what would be done, without doing it.") do |d|
35 $fu_args = { :verbose => true, :noop => true }
38 myparser.on("--file-extension EXTENSION", "-e",
39 "The file extension for the files to rename.") do |e|
42 myparser.on("--preserve-names", "-p",
43 "Preserve the names while changing the numbers.") do |e|
44 opts.preserve_names = true
49 raise "invalid num_digits: #{opts.num_digits}" unless
51 raise "must give an extension" unless opts.extension != nil
63 #.#{$opts.extension}").sort.each do |f|
65 Dir.glob("*.#{$opts.extension}").sort.each do |f|
71 $total_files = $total_files + 1
74 def get_file_name(num)
75 return sprintf("%0#{$opts.num_digits}d", num)
78 def rename_files(file)
79 FileUtils.mv(file, "#{get_file_name(1 + $total_files)}.#{$opts.extension}",
81 $total_files = $total_files + 1
84 def rename_files_keep_names(file)
86 if (file =~ /^[0-9. -]*(.*)$/) then
89 raise "can't find proper name for #{file}"
91 full_name = "#{get_file_name(1 + $total_files)} - #{proper_file}"
92 FileUtils.mv(file, full_name, $fu_args)
93 $total_files = $total_files + 1
98 $opts = MyOptions.parse(ARGV)
99 rescue Exception => msg
100 $stderr.print("#{msg}.\nType --help to see usage information.\n")
104 # make sure there aren't too many files
106 max_total_files = pow(10, $opts.num_digits) - 1
107 file_iter { |f| count_files(f) }
108 if ($total_files > max_total_files) then
109 raise "With #{$opts.num_digits} digit(s), we can only have at most \
110 #{max_total_files} files-- but there are #{$total_files} files in the \
111 #directory. Try setting a higher value for num_digits, using -D."
116 if ( $opts.preserve_names ) then
117 file_iter { |f| rename_files_keep_names(f) }
119 file_iter { |f| rename_files(f) }