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 .include? method always returns false even though I see the filename contains such search pattern. If I comment out the include? check, gsub() does not seem to generate a new file name at all (i.e. file name remains the same). So can someone please take a look at see what I did wrong? Thanks a bunch in advance!
Here is the expected behavior:
Assuming that in current folder there are three files: a1.jpg, a2.jpg, and a3.jpg
The Ruby script should be able to rename it to b1.jpg, b2.jpg, b3.jpg
#!/Users/Antony/.rvm/rubies/ruby-1.9.3-p194/bin/ruby
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))
if origin.include?(searchPattern)
newEntry = origin.gsub(target, newTarget)
File.rename( origin, newEntry )
puts "Rename from " + origin + " to " + newEntry
end
end
Slightly modified version:
Key differences:
.stripto remove the trailing newline that you get fromgets. 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 togsubandrenameinstead oforigin.originis really only useful for the.include?test. Since it’s a fragment of a filename, it can’t be used withrename. I removed theoriginvariable entirely to avoid the temptation to misuse it.For your example folder structure, entering
*.jpg,a, andbfor the three input prompts (respectively) should rename the files as you are expecting.