Current name of files:
Empty_test-one.txt, Empty_test-two.txt, Empty_test-three.txt
I just want to rename the word Empty. My code so far:
puts "Indicate new name of files":
new_name = gets.chomp
# Look for the specific files
Dir.glob("*.txt").each do |renaming|
# Renaming of files starts, but not on every file
File.rename(renaming, new_name + ".txt")
I'm currently unable to rename each individual file and keep the second part of the file (test-one, test-two, test-three).
Could you please help me?
old_part = "Empty"
puts "Indicate new name of files":
new_name = gets.chomp
# Look for the specific files
Dir.glob("*#{old_part}*.txt").each do |renaming|
full_new_name = renaming.sub(/\A(.*)#{old_part}(.*)\z/, "\\1#{new_name}\\2")
File.rename(renaming, full_new_name)
end
What you were missing was to properly build the new name of file, changing old_name
to new_name
.