I have been trying to work out a file rename program based on ruby, as a programming exercise for myself (I am aware of rename under linux, but I want to learn Ruby, and rename is not available in Mac).
From the code below, the issue is that the
puts "Enter the file search query"
searchPattern = gets
puts "Enter the target to replace"
target = gets
puts "Enter the new target name"
newTarget = gets
Dir.glob("./*").sort.each do |entry|
origin = File.basename(entry, File.extname(entry))
newEntry = origin.gsub(target, newTarget)
File.rename( origin, newEntry )
puts "Rename from " + origin + " to " + newEntry
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
.stripto remove the trailing newline that you get from
gets. Otherwise, this newline character will mess up all of your match attempts.
globcall instead of globbing for everything and then manually filtering it later.
entry(that is, the complete filename) in the calls to
originis 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
originvariable entirely to avoid the temptation to misuse it.
For your example folder structure, entering
b for the three input prompts (respectively) should rename the files as you are expecting.