Ruby File Renamer
I had to rename a lot of files today, recursively.
I found a nice script from Sarah Vessels.
I made it more general purpose (the SVN stuff is gone for example). I also tried moving with the system command mv but it didn’t work so I tried with FileUtils.mv instead which worked fine.
require 'find'
require 'fileutils'
def finder( start_dir, look_for, replace_with )
Find.find( start_dir ) do |path|
if FileTest.file?( path )
if path =~ look_for
old_name = File.basename( path )
new_name = old_name.gsub( look_for, replace_with )
dir = path.gsub( /#{old_name}/, '' )
if File.exists?( dir + old_name )
puts "#{dir + old_name} to #{dir + new_name}\n"
FileUtils.mv(dir + old_name, dir + new_name)
end
end
end
end
end
finder( '/some/dir/', /\.html$/, '.htm' )
You pass the directory you want to start with, the regular expression you want to replace with and the replacement you want to use.
Without knowing anything about the internals (like me) one can anyhow deduce that Find.find will return all sub-paths in a recursive fashion.