我需要根据用户的指示重命名多个文件的部分名称

时间:2016-02-19 16:19:27

标签: ruby renaming

文件的当前名称:

Empty_test-one.txt Empty_test-two.txt Empty_test-three.txt

我只想重命名清空这个词。到目前为止我的代码:

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") 

我目前无法重命名每个文件并保留文件的第二部分(test-one,test-two,test-three)。

你能帮我吗?

1 个答案:

答案 0 :(得分:2)

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

您缺少的是正确构建新文件名,将old_name更改为new_name