How to search a folder and all of its subfolders for files of a certain type

agentbanks217 picture agentbanks217 · Aug 17, 2010 · Viewed 53.3k times · Source

I am trying to search for all files of a given type in a given folder and copy them to a new folder.

I need to specify a root folder and search through that folder and all of its subfolders for any files that match the given type.

How do I search the root folder's subfolders and their subfolders? It seems like a recursive method would work, but I cannot implement one correctly.

Answer

rogerdpack picture rogerdpack · Aug 17, 2010

Try this:

Dir.glob("#{folder}/**/*.pdf")

which is the same as

Dir["#{folder}/**/*.pdf"]

Where the folder variable is the path to the root folder you want to search through.