From: Colin Patrick McCabe Date: Thu, 13 May 2010 03:52:09 +0000 (-0700) Subject: Add names_to_numbers script X-Git-Url: http://club.cc.cmu.edu/~cmccabe/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=48535204969cc0fdb31be8f397b9dcdb8ed86763;p=cmccabe-bin Add names_to_numbers script Add names_to_numbers script. I mainly use it for renumbering directories full of audio book mp3s. --- diff --git a/names_to_numbers.rb b/names_to_numbers.rb new file mode 100755 index 0000000..689e6de --- /dev/null +++ b/names_to_numbers.rb @@ -0,0 +1,100 @@ +#!/usr/bin/ruby -w + +# +# names_to_numbers.rb +# +# Renames all the files in a directory with the given file extension. +# The renamed files will just have numbers. +# +# Colin Mccabe +# + +require 'fileutils' +require 'optparse' +require 'ostruct' + +class MyOptions + def self.parse(args) + opts = OpenStruct.new + opts.dry_run = false + opts.num_digits = 2 + opts.extension = nil + $fu_args = { :verbose => true } + + # Fill in $opts values + parser = OptionParser.new do |myparser| + myparser.banner = "Usage: #{ File.basename($0) } [opts]" + myparser.separator("Specific options:") + myparser.on("--num-digits DIGITS", "-D", + "Set the number of digits in the numbering scheme.") do |d| + opts.num_digits = d.to_i + end + myparser.on("--dry-run", "-d", + "Show what would be done, without doing it.") do |d| + $fu_args = { :verbose => true, :noop => true } + opts.dry_run = true + end + myparser.on("--file-extension EXTENSION", "-e", + "The file extension for the files to rename.") do |e| + opts.extension = e + end + end + + parser.parse!(args) + raise "invalid num_digits: #{opts.num_digits}" unless + opts.num_digits > 0 + raise "must give an extension" unless opts.extension != nil + return opts + end +end + +def pow(x, y) + ret = 1 + (0...y).each do |z| + ret = ret * x + end + return ret +end +#.#{$opts.extension}").sort.each do |f| +def file_iter + Dir.glob("*.#{$opts.extension}").sort.each do |f| + yield f + end +end + +def count_files(file) + $total_files = $total_files + 1 +end + +def get_file_name(num) + return sprintf("%0#{$opts.num_digits}d.#{$opts.extension}", num) +end + +def rename_files(file) + FileUtils.mv(file, get_file_name(1 + $total_files), $fu_args) + $total_files = $total_files + 1 +end + +# MAIN +begin + $opts = MyOptions.parse(ARGV) +rescue Exception => msg + $stderr.print("#{msg}.\nType --help to see usage information.\n") + exit 1 +end + +# make sure there aren't too many files +$total_files = 0 +max_total_files = pow(10, $opts.num_digits) - 1 +file_iter { |f| count_files(f) } +if ($total_files > max_total_files) then + raise "With #{$opts.num_digits} digit(s), we can only have at most \ +#{max_total_files} files-- but there are #{$total_files} files in the \ +#directory. Try setting a higher value for num_digits, using -D." +end + +# rename files +$total_files = 0 +file_iter { |f| rename_files(f) } + +exit 0