问题描述
我试图在给定文件夹中搜索给定类型的所有文件(比如.pdf),并将它们复制到一个新的文件夹中。我需要能够做的是指定一个根文件夹,并搜索该文件夹及其所有子文件夹,以查找与给定类型(.pdf)相匹配的任何文件。任何人都可以给我一个关于如何通过根文件夹的子文件夹和他们的子文件夹等进行搜索的手。这听起来像一个递归的方法会在这里做的伎俩,但我不能正确实施一个? (我正在用ruby实现这个程序)。
你想要模块。 Find.find
取一个包含路径的字符串,并将父路径和每个文件和子目录的路径传递给一个伴随块。一些示例代码: require'find'
pdf_file_paths = []
Find。 find('path / to / search')do | path |
pdf_file_paths<< path if〜path =〜/.*\.pdf$/
end
递归搜索路径,并将所有以.pdf结尾的文件名存储在数组中。
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).
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.
这篇关于在文件夹及其所有子文件夹中搜索某种类型的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!