To get all files (strictly files only) recursively:
Dir.glob('path/**/*').select { |e| File.file? e }
Or anything that's not a directory (File.file? would reject non-regular files):
Dir.glob('path/**/*').reject { |e| File.directory? e }
Alternative Solution
Using Find#find over a pattern-based lookup method like Dir.glob is actually better. See this answer to "One-liner to Recursively List Directories in Ruby?".
# 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 ) }
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
def get_path_content(dir)
queue = Queue.new
result = []
queue << dir
until queue.empty?
current = queue.pop
Dir.entries(current).each { |file|
full_name = File.join(current, file)
if not (File.directory? full_name)
result << full_name
elsif file != '.' and file != '..'
queue << full_name
end
}
end
result
end
20条答案
按热度按时间b4lqfgs41#
您还可以使用以下快捷方式选项
如果您想要在任何文件夹或子文件夹中查找所有Ruby文件:
xxhby3vn2#
示例:
消息来源:http://ruby-doc.org/core/classes/Dir.html#method-c-entries
lrl1mhuk3#
以下代码片断准确地显示了目录中文件的名称,跳过了子目录和
"."
、".."
点分文件夹:uajslkp64#
To get all files (strictly files only) recursively:
Or anything that's not a directory (
File.file?
would reject non-regular files):Alternative Solution
Using
Find#find
over a pattern-based lookup method likeDir.glob
is actually better. See this answer to "One-liner to Recursively List Directories in Ruby?".hts6caw35#
这对我很管用:
如果您不想要隐藏文件[1],请使用Dir[]:
现在,目录条目将返回隐藏文件,并且您不需要通配符Asterix(您可以只传递带有目录名的变量),但它将直接返回基本名称,因此File.xxx函数将不起作用。
[1]
.dotfile
在Unix上,我不知道Windowswmtdaxz36#
在Ruby 2.5中,您现在可以使用
Dir.children
。它以数组的形式获取文件名,但“.”除外。和“..”示例:
Http://ruby-doc.org/core-2.5.0/Dir.html#method-c-children
qybjjes17#
就我个人而言,我发现这是循环浏览文件夹中的文件最有用的,具有前瞻性的安全性:
p4tfgftt8#
这是一个在目录中查找文件的解决方案:
5jdjgkvh9#
此代码仅返回带扩展名的文件名(不带全局路径)
=>[文件_1.rb,文件_2.html,文件_3.js]
vybvopom10#
在获取目录中的所有文件名时,此代码片段可用于拒绝目录[
.
,..
]和以.
开头的隐藏文件pjngdqdw11#
这就是对我有效的方法:
Dir.entries
返回字符串数组。然后,我们必须提供文件到File.file?
的完整路径,除非dir
等于我们当前的工作目录。这就是为什么这个File.join()
。ki1q1bka12#
gmol163913#
您可能还希望使用
Rake::FileList
(假设您具有rake
依赖项):根据该接口:
文件列表是懒惰的。当给定要包括在文件列表中的可能文件的全局模式的列表时,FileList保存该模式以供以后使用,而不是搜索文件结构来查找文件。
https://docs.ruby-lang.org/en/2.1.0/Rake/FileList.html
amrnrhlw14#
一种简单的方法可能是:
xxhby3vn15#
从目录和所有子目录返回文件的相对路径