Go Back to Redneck Programmer
© 2007 Robb Nicholson

file_rename.rb

Bulk file rename -- rename every file in a directory with a given basename and sequence. Useful for digital images imported from your camera, bit torrent downloads (e.g. TV show episodes), etc.

Ruby Source Code

#!/usr/bin/env ruby

require 'fileutils'
require 'find'

$verbose = false

class FileRenamer

 attr_accessor :directory

 # constructor
 def initialize(directory=".")
  @directory = directory
  FileUtils.cd(@directory, :verbose => $verbose)
 end

 #add prefix to each file in dir, ignoring directories
 def add_prefix(prefix)
  Dir.foreach(@directory) {|x| rename_file(x,"#{prefix}#{x}") }
 end
 
 #add postfix to end of each file in dir, ignoring directories
 def add_postfix(postfix)
  Dir.foreach(@directory) {|x| rename_file(x,"#{x}#{postfix}") }
 end
 
 #rename a file unless it is a directory
 def rename_file(from, to)
  print "#{from}"
  if FileTest.directory?(from)
   puts "/ remains unchanged"
  else
   FileUtils.mv(from, to, :verbose => $verbose)
   puts " changed to #{to}"
  end #if 
 end
 
 # rename all files in directory to base_name + a sequence
 def rename_with_base(base_name)
  idx = 0
  Dir.foreach(@directory) do |x|
   if !FileTest.directory?(x)
	# attempt to use same extension
    rename_file(x,"#{base_name}#{idx}#{x.slice /\..*$/}")
    idx += 1
   end
  end
 end
 
 def list_dir
  Dir.foreach(@directory) do |x|
   print "#{x}"
   if FileTest.directory?(x)
    puts "/"
   elsif FileTest.executable?(x)
    puts "*"
   elsif FileTest.symlink?(x)
    puts "->"
   end #if
  end #do
 end
end

if __FILE__ == $0  
  if ARGV.length < 2 then
    puts "Usage: #{$0} directory basename "
    exit
  end
	
  directory = ARGV.first
  puts "Directory: #{directory}"
  fn = FileRenamer.new(directory)
  #fn.list_dir
  fn.rename_with_base(ARGV[1])
  puts "Results...."
  fn.list_dir
  
end