我想使用Ruby从一个文件夹中获得所有文件名。
当前回答
如果您想获得包含符号链接的文件名数组,请使用
Dir.new('/path/to/dir').entries.reject { |f| File.directory? f }
甚至
Dir.new('/path/to/dir').reject { |f| File.directory? f }
如果你不想使用符号链接,请使用
Dir.new('/path/to/dir').select { |f| File.file? f }
如其他答案所示,如果你想递归地获得所有文件,使用dir .glob('/path/to/dir/**/*')而不是dir .new('/path/to/dir')。
其他回答
如果你用空格创建目录:
mkdir "a b"
touch "a b/c"
你不需要转义目录名,它会自动完成:
p Dir["a b/*"] # => ["a b/c"]
你可能还想使用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
在Ruby 2.5中,你现在可以使用Dir.children。它以数组的形式获取文件名,除了"."和".."
例子:
Dir.children("testdir") #=> ["config.h", "main.rb"]
http://ruby-doc.org/core-2.5.0/Dir.html#method-c-children
这段代码只返回带扩展名的文件名(没有全局路径)
Dir.children("/path/to/search/")
= > [file_1。Rb, file_2.html, file_3.js]
这是一个在目录中查找文件的解决方案:
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
推荐文章
- 是否可以在MiniTest中运行单个测试?
- 如何在Ruby中生成a和b之间的随机数?
- 如何在Python中获得所有直接子目录
- 即使模板文件存在,Flask也会引发TemplateNotFound错误
- 无法安装gem -未能建立gem本地扩展-无法加载这样的文件——mkmf (LoadError)
- 如何复制在bash所有目录和文件递归?
- 如何在Ruby中创建文件
- 什么是Ruby文件。开放模式和选项?
- Ruby数组到字符串的转换
- 如何分割(块)一个Ruby数组成X元素的部分?
- Ruby中“or”和||的区别?
- __FILE__宏显示完整路径
- 如何测试参数是否存在在轨道
- 文件名中允许的字符
- 在Ruby中不创建新字符串而修饰字符串的规范方法是什么?