6 # Renames all the files in a directory with the given file extension.
7 # The renamed files will just have numbers.
22 opts.starting_number = 1
23 $fu_args = { :verbose => true }
24 opts.preserve_names = false
26 # Fill in $opts values
27 parser = OptionParser.new do |myparser|
28 myparser.banner = "Usage: #{ File.basename($0) } [opts]"
29 myparser.separator("Specific options:")
30 myparser.on("--num-digits DIGITS", "-D",
31 "Set the number of digits in the numbering scheme.") do |d|
32 opts.num_digits = d.to_i
34 myparser.on("--dry-run", "-d",
35 "Show what would be done, without doing it.") do |d|
36 $fu_args = { :verbose => true, :noop => true }
39 myparser.on("--file-extension EXTENSION", "-e",
40 "The file extension for the files to rename.") do |e|
43 myparser.on("--preserve-names", "-p",
44 "Preserve the names while changing the numbers.") do |e|
45 opts.preserve_names = true
47 myparser.on("--starting-number NUMBER", "-N",
48 "The starting number (defaults to 1)") do |e|
49 opts.starting_number = e.to_i
54 raise "invalid num_digits: #{opts.num_digits}" unless
56 raise "must give an extension" unless opts.extension != nil
68 #.#{$opts.extension}").sort.each do |f|
70 Dir.glob("*.#{$opts.extension}").sort.each do |f|
76 $total_files = $total_files + 1
79 def get_file_name(num)
80 return sprintf("%0#{$opts.num_digits}d", num)
83 def rename_files(file)
84 dst="#{get_file_name($opts.starting_number + $total_files)}.#{$opts.extension}"
86 FileUtils.mv(file, dst, $fu_args)
88 $total_files = $total_files + 1
91 def rename_files_keep_names(file)
93 if (file =~ /^[0-9. -]*(.*)$/) then
96 raise "can't find proper name for #{file}"
98 full_name = "#{get_file_name(1 + $total_files)} - #{proper_file}"
99 FileUtils.mv(file, full_name, $fu_args)
100 $total_files = $total_files + 1
105 $opts = MyOptions.parse(ARGV)
106 rescue Exception => msg
107 $stderr.print("#{msg}.\nType --help to see usage information.\n")
111 # make sure there aren't too many files
113 max_total_files = pow(10, $opts.num_digits) - 1
114 file_iter { |f| count_files(f) }
115 if ($total_files > max_total_files) then
116 raise "With #{$opts.num_digits} digit(s), we can only have at most \
117 #{max_total_files} files-- but there are #{$total_files} files in the \
118 #directory. Try setting a higher value for num_digits, using -D."
123 if ( $opts.preserve_names ) then
124 file_iter { |f| rename_files_keep_names(f) }
126 file_iter { |f| rename_files(f) }