BibleGateway.com Verse Of The Day

Tuesday, June 12, 2007

My First Vaguely Useful Ruby Script

Alright, anyone with directories full of digital photos, mp3's, or other docs might appreciate an easy way to rename all the files in a directory, either by appending a common prefix, postfix (or extension), or giving each file the same basename with a sequence appending to the filename. There have been times I would have found that useful, and it turns out it's very easy to do with some simple Ruby scripting....


file_renamer.rb


#!/usr/bin/env ruby

require 'fileutils'
require 'find'

class FileRenamer

attr_accessor :directory

# constructor
def initialize(directory=".")
@directory = directory
FileUtils.cd(@directory, :verbose => true)
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 => false)
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)
rename_file(x,"#{base_name}#{idx}")
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

# test it...
fn = FileRenamer.new("C:/test")
fn.list_dir
fn.add_prefix("test")
fn.rename_with_base("start")
fn.add_postfix(".txt")

No comments: