English 中文(简体)
如何在红宝石中质量重命名文件
原标题:How to mass rename files in ruby
  • 时间:2012-05-25 17:14:29
  •  标签:
  • ruby

我一直试图开发一个基于红宝石的文件重命名程序, 作为我自己的编程练习(我知道在 Linux 下重新命名, 但我想学习Ruby,

从下面的代码中,问题在于 包括? 方法总是返回错误, 即使我看到文件名包含这样的搜索模式。 如果我对 包含吗? check, gsub () 似乎根本不产生新的文件名( 即文件名保持不变 ) 。 因此, 有人能看看我做错了什么吗? 感谢大家!

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
最佳回答

稍稍修改的版本 :

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

关键差异 :

  • Use .strip to remove the trailing newline that you get from gets. Otherwise, this newline character will mess up all of your match attempts.
  • Use the user-provided search pattern in the glob call instead of globbing for everything and then manually filtering it later.
  • Use entry (that is, the complete filename) in the calls to gsub and rename instead of origin. origin is 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 origin variable entirely to avoid the temptation to misuse it.

对于您的文件夹结构, 输入 , a b , 用于三个输入提示的 < code>b (分别), 应该按照您期待的重新命名文件 。

问题回答

我用公认的答案 来修正一堆复制的文件名

Dir.glob( ./* ).sort.each do |entry|
  if File.basename(entry).include?(  copy )
    newEntry = entry.gsub(  copy ,   )
    File.rename( entry, newEntry )
  end
end

Your problem is that gets returns a newline at the end of the string. So, if you type "foo" then searchPattern becomes "foo ". The simplest fix is:

searchPattern = gets.chomp

我可以略微改写你的代码:

$stdout.sync
print "Enter the file search query: "; search  = gets.chomp
print "Enter the target to replace: "; target  = gets.chomp
print "  Enter the new target name: "; replace = gets.chomp
Dir[ * ].each do |file|
  # Skip directories
  next unless File.file?(file)
  old_name = File.basename(file, .* )
  if old_name.include?(search)
    # Are you sure you want gsub here, and not sub?
    # Don t use `old_name` here, it doesn t have the extension
    new_name = File.basename(file).gsub(target,replace)
    File.rename( file, new_path )
    puts "Renamed #{file} to #{new_name}" if $DEBUG
  end
end

此处是今天我使用的简短版本( 没有模式匹配)

另存为重命名. rb 文件, 并在命令提示内运行, 使用 < enger > ruby rename.rb

count = 1
newname = "car"
Dir["/path/to/folder/*"].each do |old|
  File.rename(old, newname + count.to_s)
  count += 1
end

我有/抄本_MG_2435.JPG转换成1车、2车、...

我制作了一个小脚本 将整个 DBZ Serie 名称按季节重新命名 并执行 :

count = 1
new_name = "Dragon Ball Z S05E"
format_file = ".mkv"
Dir.glob("dragon ball Z*").each do |old_name|
  File.rename(old_name, new_name + count.to_s + format_file)
  count += 1
end

The result would be: Dragon Ball Z S05E1 Dragon Ball Z S05E2 Dragon Ball Z S05E3

In a folder, I wanted to remove the trailing underscore _ of any audio filename while keeping everything else. Sharing my code here as it might help someone. What the program does:

  1. Prompts the user for the:
    • Directory path: c:/your/path/here (make sure to use slashes /, not backslashes, , and without the final one).
    • File extension: mp3 (without the dot .)
    • Trailing characters to remove: _
  2. Looks for any file ending with c:/your/path/here/filename_.mp3 and renames it c:/your/path/here/filename.mp3 while keeping the file’s original extension.

puts  Enter directory path 

path = gets.strip

directory_path = Dir.glob("#{path}/*")

# Get file extension

puts  Enter file extension 

file_extension = gets.strip

# Get trailing characters to remove

puts  Enter trailing characters to remove 

trailing_characters = gets.strip

suffix = "#{trailing_characters}.#{file_extension}"

# Rename file if condition is met

directory_path.each do |file_path|
  next unless file_path.end_with?(suffix)

  File.rename(file_path, "#{file_path.delete_suffix(suffix)}.#{file_extension}")
end




相关问题
Ruby parser in Java

The project I m doing is written in Java and parsers source code files. (Java src up to now). Now I d like to enable parsing Ruby code as well. Therefore I am looking for a parser in Java that parses ...

rails collection_select vs. select

collection_select and select Rails helpers: Which one should I use? I can t see a difference in both ways. Both helpers take a collection and generates options tags inside a select tag. Is there a ...

RubyCAS-Client question: Rails

I ve installed RubyCAS-Client version 2.1.0 as a plugin within a rails app. It s working, but I d like to remove the ?ticket= in the url. Is this possible?

Ordering a hash to xml: Rails

I m building an xml document from a hash. The xml attributes need to be in order. How can this be accomplished? hash.to_xml

multiple ruby extension modules under one directory

Can sources for discrete ruby extension modules live in the same directory, controlled by the same extconf.rb script? Background: I ve a project with two extension modules, foo.so and bar.so which ...

Text Editor for Ruby-on-Rails

guys which text editor is good for Rubyonrails? i m using Windows and i was using E-Texteditor but its not free n its expired now can anyone plese tell me any free texteditor? n which one is best an ...

热门标签