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:
Post a Comment