2

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.

richsoni
  • 4,188
  • 8
  • 34
  • 47
  • See http://stackoverflow.com/q/2370702/128421. While not an exact duplicate it covers the various ways of scanning a directory. Settle on one of those, and you can craft a solution easily. – the Tin Man May 27 '16 at 19:42

3 Answers3

4

You could use Dir.glob or Dir[]:

Dir['the_directory/**/the_filename']

The ** matches 0 or more directories recursively. It returns an array of filenames that match.

matt
  • 78,533
  • 8
  • 163
  • 197
4

You can use Dir.glob, for example:

Dir.glob(File.join("**","*.rb"))

It will recursively look for "*.rb" files in your current directory.

lhdv
  • 146
  • 1
  • 6
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.