英文:
remove numeric characters from filenames with ruby
问题
早上好。我需要编写一个Ruby脚本来从文件夹中的文件名中删除数字字符。它能够工作,但不幸的是,一些文件被删除了,因为一旦删除数字字符,它们将具有相同的名称,或者它们将变为空白。我尝试添加一个条件来避免这种情况,但是现在没有任何文件被重命名。你能帮助我吗?这是代码:
require 'fileutils'
folder = ARGV[0]
Dir.chdir(folder)
Dir.glob("*.*") do |file|
new_name = file.gsub(/[0-9]/, "")
FileUtils.mv(file, new_name) if !file.empty? && !File.exist?(file)
end
提前感谢。
英文:
Good morning everyone. I need to write a Ruby script to remove numeric characters from file names in a folder. It works, but unfortunately some files are deleted, because once the numeric characters are removed they would have the same name, or they would be empty. I tried to insert a condition to avoid it, but nothing is renamed anymore. Can you help me? This is the code:
require 'fileutils'
folder = ARGV[0]
Dir.chdir(folder)
Dir.glob("*.*") do |file|
new_name = file.gsub(/[0-9]/, "")
FileUtils.mv(file, new_name) if !file.empty? && !File.exist?(file)
end
Thanks in advance.
答案1
得分: 2
我相信你的意思是要写成这样:
!new_name.empty? && !File.exist?(new_name)
而不是这样:
!file.empty? && !File.exist?(file)
不再重命名任何东西
因为脚本原来是在说“不要重命名任何已经存在的文件” 😊
英文:
I believe you mean to write this:
!new_name.empty? && !File.exist?(new_name)
Instead of this:
!file.empty? && !File.exist?(file)
> nothing is renamed anymore
... Because the script was saying "don't rename any files that exist" 😅
答案2
得分: 0
以下是您要翻译的内容:
要进一步扩展现有的答案,您应该检查并报告是否满足某些条件。通过将内容打印到 STDERR
,您可以选择将这些错误静音,或者让它们被打印出来。
require 'fileutils'
folder = ARGV[0]
Dir.chdir(folder)
Dir.glob("*.*") do |file|
new_name = file.gsub(/[0-9]/, "")
if new_name.empty?
STDERR.puts "ERR: #{file}: new file name would be empty."
elsif File.exist?(new_name)
STDERR.puts "ERR: #{file}: moving to #{new_name} would overwrite existing file."
else
FileUtils.mv(file, new_name)
end
end
请注意,我已经将代码中的 HTML 实体编码(例如 "
)还原为原始字符,以便更容易阅读。
英文:
To expand on the existing answer, you should check and report back if certain conditions are met. By printing to STDERR
you can silence those errors if you choose, or have them printed.
require 'fileutils'
folder = ARGV[0]
Dir.chdir(folder)
Dir.glob("*.*") do |file|
new_name = file.gsub(/[0-9]/, "")
if new_name.empty?
STDERR.puts "ERR: #{file}: new file name would be empty."
elsif File.exist?(new_name)
STDERR.puts "ERR: #{file}: moving to #{new_name} would overwrite existing file."
else
FileUtils.mv(file, new_name)
end
end
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论