I am attempting to find a file by its name within a directory. I am not sure what the best approach to this problem is. The file could be nested in other directories within the root directory.
我正在尝试在一个目录中按文件名查找文件。我不知道解决这个问题的最佳方法是什么。该文件可以嵌套在根目录的其他目录中。
3 个解决方案
#1
4
You can use Dir.glob, for example:
您可以使用Dir。一团,例如:
Dir.glob(File.join("**","*.rb"))
It will recursively look for "*.rb" files in your current directory.
它会递归地寻找“*”。当前目录中的rb文件。
#2
3
this should work for you:
这应该对你有用:
require 'find'
file_name = /log\Z/
path = './'
found_files = Find.find(path).inject([]) do |files, entry|
File.file?(entry) && File.basename(entry) =~ file_name ?
files << entry : files
end
p found_files
#=> ["./Maildir/dovecot.index.log", "./pgadmin.log"]
change file_name
and path
to your needs.
根据需要更改file_name和路径。
#3
#1
4
You can use Dir.glob, for example:
您可以使用Dir。一团,例如:
Dir.glob(File.join("**","*.rb"))
It will recursively look for "*.rb" files in your current directory.
它会递归地寻找“*”。当前目录中的rb文件。
#2
3
this should work for you:
这应该对你有用:
require 'find'
file_name = /log\Z/
path = './'
found_files = Find.find(path).inject([]) do |files, entry|
File.file?(entry) && File.basename(entry) =~ file_name ?
files << entry : files
end
p found_files
#=> ["./Maildir/dovecot.index.log", "./pgadmin.log"]
change file_name
and path
to your needs.
根据需要更改file_name和路径。