如何在文件夹及其所有子文件夹中搜索特定类型的文件 [英] How to search a folder and all of its subfolders for files of a certain type

查看:62
本文介绍了如何在文件夹及其所有子文件夹中搜索特定类型的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在给定文件夹中搜索给定类型的所有文件,并将它们复制到一个新文件夹中.

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.

推荐答案

您想要 查找 模块.Find.find 接受一个包含路径的字符串,并将父路径与每个文件和子目录的路径一起传递给伴随的块.一些示例代码:

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

这将递归搜索路径,并将所有以 .pdf 结尾的文件名存储在一个数组中.

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

这篇关于如何在文件夹及其所有子文件夹中搜索特定类型的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆