Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 363
ab217 Avatar asked Aug 17 '10 00:08

ab217


People also ask

How do I search all folders and subfolders?

To search for files in File Explorer, open File Explorer and use the search box to the right of the address bar. Tap or click to open File Explorer. Search looks in all folders and subfolders within the library or folder you're viewing.

How do you find all of a certain file type?

You can use the filetype: operator in Google Search to limit results to a specific file type. For example, filetype:rtf galway will search for RTF files with the term "galway" in them.

What command would search the current directory and sub directories for a files with the .txt extension?

Replace "pattern" with a filename or matching expression, such as "*. txt" .

How can I get a list of all the subfolders and files present in a directory using PHP?

PHP using scandir() to find folders in a directory The scandir function is an inbuilt function that returns an array of files and directories of a specific directory. It lists the files and directories present inside the path specified by the user.


2 Answers

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.

like image 66
rogerdpack Avatar answered Sep 24 '22 17:09

rogerdpack


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:

require 'find'  pdf_file_paths = [] Find.find('path/to/search') do |path|   pdf_file_paths << path if path =~ /.*\.pdf$/ end 

That will recursively search a path, and store all file names ending in .pdf in an array.

like image 28
jergason Avatar answered Sep 24 '22 17:09

jergason