names_to_numbers.rb: add "preserve names" option
authorColin Patrick McCabe <cmccabe@alumni.cmu.edu>
Mon, 11 Oct 2010 03:55:12 +0000 (20:55 -0700)
committerColin Patrick McCabe <cmccabe@alumni.cmu.edu>
Mon, 11 Oct 2010 03:55:12 +0000 (20:55 -0700)
names_to_numbers.rb

index 689e6de..9439fd1 100755 (executable)
@@ -20,6 +20,7 @@ class MyOptions
     opts.num_digits = 2
     opts.extension = nil
     $fu_args = { :verbose => true }
+    opts.preserve_names = false
 
     # Fill in $opts values
     parser = OptionParser.new do |myparser|
@@ -38,6 +39,10 @@ class MyOptions
               "The file extension for the files to rename.") do |e|
         opts.extension = e
       end
+      myparser.on("--preserve-names", "-p",
+              "Preserve the names while changing the numbers.") do |e|
+        opts.preserve_names = true
+      end
     end
 
     parser.parse!(args)
@@ -67,11 +72,24 @@ def count_files(file)
 end
 
 def get_file_name(num)
-  return sprintf("%0#{$opts.num_digits}d.#{$opts.extension}", num)
+  return sprintf("%0#{$opts.num_digits}d", num)
 end
 
 def rename_files(file)
-  FileUtils.mv(file, get_file_name(1 + $total_files), $fu_args)
+  FileUtils.mv(file, "#{get_file_name(1 + $total_files)}.#{$opts.extension}",
+               $fu_args)
+  $total_files = $total_files + 1
+end
+
+def rename_files_keep_names(file)
+  proper_file = ""
+  if (file =~ /^[0-9. -]*(.*)$/) then
+    proper_file = $1
+  else
+    raise "can't find proper name for #{file}"
+  end
+  full_name = "#{get_file_name(1 + $total_files)} - #{proper_file}"
+  FileUtils.mv(file, full_name, $fu_args)
   $total_files = $total_files + 1
 end
 
@@ -95,6 +113,10 @@ end
 
 # rename files
 $total_files = 0
-file_iter { |f| rename_files(f) }
+if ( $opts.preserve_names ) then
+  file_iter { |f| rename_files_keep_names(f) }
+else
+  file_iter { |f| rename_files(f) }
+end
 
 exit 0