I am trying to search for all files of a given type (say .pdf) in a given folder and copy them to a new folder. What I need to be able to do is to specify a root folder and search through that folder and all of its subfolders for any files that match the given type (.pdf). Can anyone give me a hand on how I should search through the root folder's subfolders and their subfolders and so on. It sounds like a recursive method would do the trick here, but I cannot implement one correctly? (I am implementing this program in ruby by the way).
相关问题
- PHP Recursively File Folder Scan Sorted by Modific
- How to specify memcache server to Rack::Session::M
- Why am I getting a “C compiler cannot create execu
- reference to a method?
- ruby 1.9 wrong file encoding on windows
相关文章
- How to replace file-access references for a module
- Ruby using wrong version of openssl
- Difference between Thread#run and Thread#wakeup?
- how to call a active record named scope with a str
- “No explicit conversion of Symbol into String” for
- Segmentation fault with ruby 2.0.0p247 leading to
- How to detect if an element exists in Watir
- uninitialized constant Mysql2::Client::SECURE_CONN
You want the Find module.
Find.find
takes a string containing a path, and will pass the parent path along with the path of each file and sub-directory to an accompanying block. Some example code:That will recursively search a path, and store all file names ending in .pdf in an array.
As a small improvement to Jergason and Matt's answer above, here's how you can condense to a single line:
This uses the Find method as above, but leverages the fact that the result is an enumerable (and as such we can use select) to get an array back with the set of matches
Try this:
which is the same as
Where the folder variable is the path to the root folder you want to search through.
If speed is a concern, prefer
Dir.glob
overFind.find
.Using
ruby 2.2.2p95 (2015-04-13 revision 50295) [x86_64-darwin15]