Jam*_*ers 13 ruby recursion rake
我试图根据给定路径中包含的所有目录中的模式删除文件.我有以下但它就像一个无限循环.当我取消循环时,不会删除任何文件.我哪里错了?
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$/)
Ben*_*Lee 33
您无需重新实施此轮.递归文件glob已经是核心库的一部分.
Dir.glob('C:\Test_Directory\**\*.cs').each { |f| File.delete(f) }
Dir#glob列出目录中的文件,并且可以接受通配符.**是一个超级通配符,意思是"匹配任何东西,包括整个目录树",因此它将匹配任何级别的深度(包括"无"级别深度:.cs文件C:\Test_Directory本身也将使用我提供的模式匹配).
@kkurian指出(在评论中)File#delete可以接受列表,因此可以简化为:
File.delete(*Dir.glob('C:\Test_Directory\**\*.cs'))
mae*_*ics 12
由于您已经使用Rake,因此您可以使用方便的FileList对象.例如:
require 'rubygems'
require 'rake'
FileList['c:/Test_Directory/**/*.cs'].each {|x| File.delete(x)}
kit*_*ite 11
另一个ruby one liner快捷方式,使用FileUtils递归删除目录下的文件
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"] 
| 归档时间: | 
 | 
| 查看次数: | 7898 次 | 
| 最近记录: |