Friday, March 13, 2009

Recursive File Finder

When looking for a bunch of files somewhere in directory structure I usually pull my hear out. But I found this cool ruby code called 'Find'. It pretty much does all the dirty work for us and its packed with ruby core. It has two methods. Find.find which takes a block and will basically recursively look through every child directory of the one you pass in. Find.prune which only makes sense in the context of a find block, and just says stop looking in here. You want to make sure you use this when you hit a file or a directory you don't want to look in.

Below is a little snippet of code I wrote to recursively find files that matched some substring. It's used like this:


File.recursive_find('/root/search/path', 'invoice')


This will find all of the files that match the string 'invoice' somewhere in their name and return an array of these files. Here's the code:


require 'find'
class File
def self.recursive_find(dir, match_string)
results = []
Find.find(dir) do |path|
unless FileTest.directory?(path)
unless File.basename(path) =~ /#{match_string}/
Find.prune
else
results << path
end
else
next
end
end
results
end
end

No comments:

Post a Comment