How to search a folder and all of its subfolders for files of a certain type

前端 未结 5 717
無奈伤痛
無奈伤痛 2020-11-29 22:19

I am trying to search for all files of a given type in a given folder and copy them to a new folder.

I need to specify a root folder and search through that folder a

5条回答
  •  我在风中等你
    2020-11-29 22:46

    If speed is a concern, prefer Dir.glob over Find.find.

    Warming up --------------------------------------
               Find.find   124.000  i/100ms
                Dir.glob   515.000  i/100ms
    Calculating -------------------------------------
               Find.find      1.242k (± 4.7%) i/s -      6.200k in   5.001398s
                Dir.glob      5.249k (± 4.5%) i/s -     26.265k in   5.014632s
    
    Comparison:
                Dir.glob:     5248.5 i/s
               Find.find:     1242.4 i/s - 4.22x slower
    

     

    require 'find'
    require 'benchmark/ips'
    
    dir = '.'
    
    Benchmark.ips do |x|
      x.report 'Find.find' do
        Find.find(dir).select { |f| f =~ /\*\.pdf/ }
      end
    
      x.report 'Dir.glob' do
        Dir.glob("#{dir}/**/*\.pdf")
      end
    
      x.compare!
    end
    

    Using ruby 2.2.2p95 (2015-04-13 revision 50295) [x86_64-darwin15]

提交回复
热议问题