【问题标题】:Recursive Patterned File Delete in Ruby/RakeRuby/Rake 中的递归模式文件删除
【发布时间】:2011-10-05 21:48:39
【问题描述】:

我正在尝试从给定路径中包含的所有目录中删除基于模式的文件。我有以下内容,但它就像一个无限循环。当我取消循环时,不会删除任何文件。我哪里错了?

def recursive_delete (dirPath, pattern)
    if (defined? dirPath and  defined? pattern && File.exists?(dirPath))
        stack = [dirPath]

        while !stack.empty?
            current = stack.delete_at(0)
            Dir.foreach(current) do |file|
                if File.directory?(file)
                    stack << current+file
                else
                    File.delete(dirPath + file) if (pattern).match(file)
                end
            end
        end

    end
end

# to call:
recursive_delete("c:\Test_Directory\", /^*.cs$/)

【问题讨论】:

  • 在目录递归中,通常要处理“.”。和“..”以一种特殊的方式。如果不这样做,就会经常发生无限循环。

标签: ruby recursion rake


【解决方案1】:

您不需要重新实现这个轮子。递归文件 glob 已经是核心库的一部分。

Dir.glob('C:\Test_Directory\**\*.cs').each { |f| File.delete(f) }

Dir#glob 列出目录中的文件并且可以接受通配符。 ** 是一个超级通配符,意思是“匹配任何东西,包括整个目录树”,因此它将匹配任何深度级别(包括“无”深度级别:C:\Test_Directory 中的 .cs 文件本身也将使用我提供的模式)。

@kkurian 指出(在 cmets 中)File#delete 可以接受一个列表,所以这可以简化为:

File.delete(*Dir.glob('C:\Test_Directory\**\*.cs'))

【讨论】:

  • 酷,我没有意识到Dir#glob 支持** 通配符。
  • 同意……总比重新发明轮子好。谢谢
  • 更严格:File.delete(*Dir.glob('C:\Test_Directory\**\*.cs'))
  • @kkurian 谢谢,我将您的建议添加到我的回答中。
【解决方案2】:

由于您已经在使用 Rake,您可以使用方便的 FileList 对象。例如:

require 'rubygems'
require 'rake'

FileList['c:/Test_Directory/**/*.cs'].each {|x| File.delete(x)}

【讨论】:

    【解决方案3】:

    另一个使用 FileUtils 递归删除目录下文件的 ruby​​ one liner 快捷方式

    FileUtils.rm Dir.glob("c:/temp/**/*.so")
    

    更短:

    FileUtils.rm Dir["c:/temp/**/*.so"]
    

    另一个复杂的用法:多个模式(不同目录中的多个扩展名)。警告你不能使用 Dir.glob()

    FileUtils.rm Dir["c:/temp/**/*.so","c:/temp1/**/*.txt","d:/temp2/**/*.so"] 
    

    【讨论】:

      【解决方案4】:

      由于您使用的是 Rake,我将使用 clean 任务删除文件:

      require 'rake/clean'
      outfiles = Rake::FileList.new("**/*.out")
      CLEAN << outfiles
      

      现在,如果您运行 rake -T,您将看到我们有一个 clean 和一个 clobber 任务。

      rake clean    # Remove any temporary products
      rake clobber  # Remove any generated files
      

      如果您运行rake clean,它将删除所有带有.out 扩展名的文件。

      使用这种方法,您可以选择删除临时文件或生成的文件。使用任务clobber 删除生成的文件,如下所示:

      CLOBBER << Rake::FileList.new("**/*.gen")
      

      你可以看到他对这些任务的定义on the source code here

      【讨论】:

        猜你喜欢
        • 2011-01-02
        • 1970-01-01
        • 1970-01-01
        • 2012-10-18
        • 2011-12-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多