我想使用Ruby从一个文件夹中获得所有文件名。


当前回答

如果你用空格创建目录:

mkdir "a b"
touch "a b/c"

你不需要转义目录名,它会自动完成:

p Dir["a b/*"] # => ["a b/c"]

其他回答

除了这篇文章中的建议,我想提到的是,如果你也需要返回点文件(。gitignore等),与Dir。Glob你需要包括一个标志,如下所示: Dir。一团(“/道路/ / dir / *”,文件::FNM_DOTMATCH) 默认为Dir。条目包括点文件,以及当前的父目录。

对于感兴趣的人,我很好奇这里的答案在执行时间上是如何比较的,下面是针对深度嵌套层次结构的结果。前三个结果是非递归的:

       user     system      total        real
Dir[*]: (34900 files stepped over 100 iterations)
  0.110729   0.139060   0.249789 (  0.249961)
Dir.glob(*): (34900 files stepped over 100 iterations)
  0.112104   0.142498   0.254602 (  0.254902)
Dir.entries(): (35600 files stepped over 100 iterations)
  0.142441   0.149306   0.291747 (  0.291998)
Dir[**/*]: (2211600 files stepped over 100 iterations)
  9.399860  15.802976  25.202836 ( 25.250166)
Dir.glob(**/*): (2211600 files stepped over 100 iterations)
  9.335318  15.657782  24.993100 ( 25.006243)
Dir.entries() recursive walk: (2705500 files stepped over 100 iterations)
 14.653018  18.602017  33.255035 ( 33.268056)
Dir.glob(**/*, File::FNM_DOTMATCH): (2705500 files stepped over 100 iterations)
 12.178823  19.577409  31.756232 ( 31.767093)

它们是由以下基准测试脚本生成的:

require 'benchmark'
base_dir = "/path/to/dir/"
n = 100
Benchmark.bm do |x|
  x.report("Dir[*]:") do
    i = 0
    n.times do
      i = i + Dir["#{base_dir}*"].select {|f| !File.directory? f}.length
    end
    puts " (#{i} files stepped over #{n} iterations)"
  end
  x.report("Dir.glob(*):") do
    i = 0
    n.times do
      i = i + Dir.glob("#{base_dir}/*").select {|f| !File.directory? f}.length
    end
    puts " (#{i} files stepped over #{n} iterations)"
  end
  x.report("Dir.entries():") do
    i = 0
    n.times do
      i = i + Dir.entries(base_dir).select {|f| !File.directory? File.join(base_dir, f)}.length
    end
    puts " (#{i} files stepped over #{n} iterations)"
  end
  x.report("Dir[**/*]:") do
    i = 0
    n.times do
      i = i + Dir["#{base_dir}**/*"].select {|f| !File.directory? f}.length
    end
    puts " (#{i} files stepped over #{n} iterations)"
  end
  x.report("Dir.glob(**/*):") do
    i = 0
    n.times do
      i = i + Dir.glob("#{base_dir}**/*").select {|f| !File.directory? f}.length
    end
    puts " (#{i} files stepped over #{n} iterations)"
  end
  x.report("Dir.entries() recursive walk:") do
    i = 0
    n.times do
      def walk_dir(dir, result)
        Dir.entries(dir).each do |file|
          next if file == ".." || file == "."

          path = File.join(dir, file)
          if Dir.exist?(path)
            walk_dir(path, result)
          else
            result << file
          end
        end
      end
      result = Array.new
      walk_dir(base_dir, result)
      i = i + result.length
    end
    puts " (#{i} files stepped over #{n} iterations)"
  end
  x.report("Dir.glob(**/*, File::FNM_DOTMATCH):") do
    i = 0
    n.times do
      i = i + Dir.glob("#{base_dir}**/*", File::FNM_DOTMATCH).select {|f| !File.directory? f}.length
    end
    puts " (#{i} files stepped over #{n} iterations)"
  end
end

文件计数的差异是由于Dir。默认情况下包含隐藏文件的条目。Dir。在这种情况下,由于需要重新构建文件的绝对路径以确定文件是否为目录,条目最终花费的时间要长一些,但即使没有这一点,在递归情况下,它仍然比其他选项花费的时间要长。这都是在OSX上使用ruby 2.5.1完成的。

你可能还想使用Rake::FileList(如果你有Rake依赖):

FileList.new('lib/*') do |file|
  p file
end

根据API:

filelist是懒惰的。当给出可能的glob模式列表时 要包含在文件列表中的文件,而不是搜索文件 结构来查找文件,FileList保存后者的模式 使用。

https://docs.ruby-lang.org/en/2.1.0/Rake/FileList.html

当加载操作目录中的所有文件名时,您可以使用

Dir.glob (*)

这将返回应用程序正在运行的上下文中的所有文件(注意,对于Rails,这是应用程序的顶级目录)

您可以在这里(https://ruby-doc.org/core-2.7.1/Dir.html#method-c-glob)进行额外的匹配和递归搜索

这是一个在目录中查找文件的解决方案:

files = Dir["/work/myfolder/**/*.txt"]

files.each do |file_name|
  if !File.directory? file_name
    puts file_name
    File.open(file_name) do |file|
      file.each_line do |line|
        if line =~ /banco1/
          puts "Found: #{line}"
        end
      end
    end
  end
end

这对我来说很管用:

如果你不想要隐藏文件[1],使用Dir[]:

# With a relative path, Dir[] will return relative paths 
# as `[ './myfile', ... ]`
#
Dir[ './*' ].select{ |f| File.file? f } 

# Want just the filename?
# as: [ 'myfile', ... ]
#
Dir[ '../*' ].select{ |f| File.file? f }.map{ |f| File.basename f }

# Turn them into absolute paths?
# [ '/path/to/myfile', ... ]
#
Dir[ '../*' ].select{ |f| File.file? f }.map{ |f| File.absolute_path f }

# With an absolute path, Dir[] will return absolute paths:
# as: [ '/home/../home/test/myfile', ... ]
#
Dir[ '/home/../home/test/*' ].select{ |f| File.file? f }

# Need the paths to be canonical?
# as: [ '/home/test/myfile', ... ]
#
Dir[ '/home/../home/test/*' ].select{ |f| File.file? f }.map{ |f| File.expand_path f }

现在,Dir。条目将返回隐藏的文件,并且您不需要通配符asterix(您可以直接将目录名传递给变量),但它将直接返回basename,因此File. xml将返回文件。XXX函数不能工作。

# In the current working dir:
#
Dir.entries( '.' ).select{ |f| File.file? f }

# In another directory, relative or otherwise, you need to transform the path 
# so it is either absolute, or relative to the current working dir to call File.xxx functions:
#
home = "/home/test"
Dir.entries( home ).select{ |f| File.file? File.join( home, f ) }

[1] .dotfile在unix上,我不知道Windows上