Everyday Ruby Scripting - Renaming Files

I recently had the need to replace around 50 files. However, the new files did not have the same name as the old files.

The old files had names like:

AD5001.indd
AD5002.indd
AD5003.indd

and the new files had names like:

AD5001_rev.indd
AD5002_rev.indd
AD5003_rev.indd

The solution was a quick ruby script:

require 'fileutils'
rev_files = Dir.glob("./**/*_rev*.indd")
 
rev_files.each do |rf|
  orig_file = rf.gsub("_rev","")
  FileUtils.rm(orig_file)
  FileUtils.mv(rf,orig_file)
  puts "Replaced #{orig_file} with #{rf}"
end

Originally, I was going to use some combination of Emacs and find-dired, but ultimately this proved simpler.

Leave a Reply