【问题标题】:How to rename particular files in the folder for ruby如何为ruby重命名文件夹中的特定文件
【发布时间】:2014-04-23 07:58:59
【问题描述】:

我有一个文件夹,考虑它的位置是/home/itsme/videos。文件夹包含许多文件(扩展名为 .txt、.rb、.mp4 等的文件)。

但从这些文件中,我只需要重命名 .mp4 文件。我想当场重命名文件,而不移动它们。如何使用 ruby 实现这一点。

为此,我使用的是 ruby​​ 1.9.3

【问题讨论】:

  • 你需要优化代码,因为我的答案有效。
  • 所有这些都是工作代码,您必须按照 Monk_Code 的建议配置它

标签: ruby-on-rails ruby ruby-1.9.3 ruby-1.9


【解决方案1】:

这将是诡计,这里我使用FileUtils.mv 方法。

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

要使用 FileUtils 类 方法,您必须使用 require fileutils 包含它

【讨论】:

  • 让我知道对此的反馈。
【解决方案2】:

请尝试这样:

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

【讨论】:

    【解决方案3】:
    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
    

    与金士顿的回答相同,但对要求非常具体。 这将跳过任何不是 MP4 的内容并用新名称重命名 mp4 文件。 希望这会有所帮助。

    【讨论】:

    • 我厌倦了你的解决方案,但它给了我Errno::ENOENT: No such file or directory。尽管存在很多 .mp4 文件。
    • 您是否指定了正确的目录路径??我已经测试过这个解决方案,它适用于我,尝试指定绝对路径而不是相对路径。
    【解决方案4】:

    如果 File#rename 返回 0 表示文件已重命名,请尝试此操作,如果文件无法重命名,则引发 SystemCallErrorDir["./home/itsme/videos/*.mp4"] 返回此 mp4 扩展名的文件数组:

    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
    

    【讨论】:

      【解决方案5】:

      试一试:

      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
      

      参考:http://www.ruby-doc.org/core-2.1.1/File.html#method-c-renamehttp://www.ruby-doc.org/core-2.1.1/Dir.html

      希望这可行:)

      【讨论】:

        猜你喜欢
        • 2012-10-18
        • 2021-10-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-15
        • 2018-07-17
        • 2012-01-02
        • 2017-11-14
        相关资源
        最近更新 更多