如何在文件夹及其所有子文件夹中搜索特定类型的文件
我试图在给定文件夹中搜索给定类型的所有文件并将它们复制到新文件夹。
我需要指定一个根文件夹,并在该文件夹及其所有子文件夹中搜索与给定类型匹配的任何文件。
如何搜索根文件夹的子文件夹及其子文件夹?看起来递归方法可行,但我无法正确实现。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果考虑速度,请优先选择
Dir.glob
而不是Find.find
。使用 ruby 2.2.2p95(2015-04-13 修订版 50295)[x86_64-darwin15]
If speed is a concern, prefer
Dir.glob
overFind.find
.Using
ruby 2.2.2p95 (2015-04-13 revision 50295) [x86_64-darwin15]
作为对上面 Jergason 和 Matt 的答案的一个小改进,以下是如何将其压缩为一行:
这使用了上面的 Find 方法,但利用了结果是可枚举的这一事实(因此我们可以使用 select)来获取包含一组匹配项的数组
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.
您需要 Find 模块。 Find.find 接受包含路径的字符串,并将父路径以及每个文件和子目录的路径传递到随附的块。一些示例代码:
这将递归搜索路径,并将所有以 .pdf 结尾的文件名存储在数组中。
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.