How to mass rename files in ruby

Slightly modified version:

puts "Enter the file search query"
searchPattern = gets.strip
puts "Enter the target to replace"
target = gets.strip
puts "Enter the new target name"
newTarget = gets.strip
Dir.glob(searchPattern).sort.each do |entry|
  if File.basename(entry, File.extname(entry)).include?(target)
    newEntry = entry.gsub(target, newTarget)
    File.rename( entry, newEntry )
    puts "Rename from " + entry + " to " + newEntry
  end
end

Key differences:

  • Use .strip to remove the trailing newline that you get from gets. Otherwise, this newline character will mess up all of your match attempts.
  • Use the user-provided search pattern in the glob call instead of globbing for everything and then manually filtering it later.
  • Use entry (that is, the complete filename) in the calls to gsub and rename instead of origin. origin is really only useful for the .include? test. Since it's a fragment of a filename, it can't be used with rename. I removed the origin variable entirely to avoid the temptation to misuse it.

For your example folder structure, entering *.jpg, a, and b for the three input prompts (respectively) should rename the files as you are expecting.


I used the accepted answer to fix a bunch of copied files' names.

Dir.glob('./*').sort.each do |entry|
  if File.basename(entry).include?(' copy')
    newEntry = entry.gsub(' copy', '')
    File.rename( entry, newEntry )
  end
end

Tags:

Ruby