Skip to main content
1 of 2
Inaimathi
  • 2.2k
  • 12
  • 24

File Renaming with Ruby

This is a minimal little utility that I've found useful while reorganizing my music and book libraries. Any issues you can see? Anything I could be doing better or more elegantly? Anyone wanna take a crack at the equivalent in Python/Perl?

#! /usr/bin/ruby

require 'optparse'
require 'pp'
require 'fileutils'

options = {:sub => "", :downcase => nil}
optparse = OptionParser.new do |opts|
  opts.on('-r', '--regex REGEX', String, 'Specify the regular expression to replace'){|options[:regex]|}
      opts.on('-s', '--sub SUBSTITUTE', String, 'Specify what to replace the match with. By default, the empty string (so the matched patterns are stripped).'){|options[:sub]|}
  opts.on('-d', '--downcase', 'If passed, all filenames will be downcased.'){|options[:downcase]|}
end
optparse.parse!

ARGV.each do |target|
  new_name = target.gsub(/#{options[:regex]}/, options[:sub])

  if options[:downcase] 
    new_name.downcase!
  end
    
  File.rename(target, new_name)
end
Inaimathi
  • 2.2k
  • 12
  • 24