Вопрос

I have a folder, consider its location is /home/itsme/videos. Folder contains many files (files with extension .txt, .rb, .mp4 etc).

But from that files I have to rename only .mp4 files. I'd like to rename the files on the spot, without moving them. How can I achieve this using ruby.

For this I am using ruby 1.9.3

Это было полезно?

Решение

This is going to be trick, here I am using FileUtils.mv method.

path = "/home/itsme/videos"
Dir.open(path).each do |p|
  next if File.extname(p) != ".mp4"
  filename = File.basename(p, File.extname(p))
  newname = filename.upcase + File.extname(p)  
  FileUtils.mv("#{path}/#{p}", "#{path}/#{newname}")
end

To use FileUtils class method you have to include it by using require fileutils

Другие советы

Please try like this:

path = "/home/itsme/videos"
Dir.open(path).each do |p|
 next if p.match(/^\./)
 old = path + "\\" + p
 new = path + "\\" + p.downcase.gsub(' ', '-')
 File.rename(old, new)
 puts old + " => " + new
end
path = "/home/itsme/videos"
  Dir.open(path).each do |p|
  next if File.extname(p) != ".mp4"
  // Renaming happens here
  new = path + "\\" + p.downcase.gsub(' ', '-')
  File.rename(p, new)
end

Same as Kingston's Answer but very specific to the requiements. This will skip anything that is not MP4 and rename the mp4 file with the new name. Hope this helps.

Try this if File#rename return 0 that mean file renamed and raises a SystemCallError if the file cannot be renamed. Dir["./home/itsme/videos/*.mp4"] return array of files this mp4 extension:

Dir["./home/itsme/videos/*.mp4"].each do |file|
  begin
  if File.rename(file, "new_filename").zero?
    puts "Change name #{file}"
  end
  rescue SystemCallError
    puts "Can't rename #{file}"
  end
end

Just Try:

Dir.chdir("/home/itsme/videos") do
    unless Dir.glob("*.{mp4}").empty?
        Dir.glob("*.mp4", File::FNM_DOTMATCH).each_with_index do |file, index|
            File.rename(Dir.glob("*.mp4", File::FNM_DOTMATCH)[index],"some_other_name_#{index}.mp4")            
        end
    end
end

Ref: http://www.ruby-doc.org/core-2.1.1/File.html#method-c-rename, http://www.ruby-doc.org/core-2.1.1/Dir.html

Hope this works :)

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top