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 dst="#{get_file_name(1 + $total_files)}.#{$opts.extension}"
81 FileUtils.mv(file, dst, $fu_args)
83 $total_files = $total_files + 1
86 def rename_files_keep_names(file)
88 if (file =~ /^[0-9. -]*(.*)$/) then
91 raise "can't find proper name for #{file}"
93 full_name = "#{get_file_name(1 + $total_files)} - #{proper_file}"
94 FileUtils.mv(file, full_name, $fu_args)
95 $total_files = $total_files + 1
100 $opts = MyOptions.parse(ARGV)
101 rescue Exception => msg
102 $stderr.print("#{msg}.\nType --help to see usage information.\n")
106 # make sure there aren't too many files
108 max_total_files = pow(10, $opts.num_digits) - 1
109 file_iter { |f| count_files(f) }
110 if ($total_files > max_total_files) then
111 raise "With #{$opts.num_digits} digit(s), we can only have at most \
112 #{max_total_files} files-- but there are #{$total_files} files in the \
113 #directory. Try setting a higher value for num_digits, using -D."
118 if ( $opts.preserve_names ) then
119 file_iter { |f| rename_files_keep_names(f) }
121 file_iter { |f| rename_files(f) }