How do I grab all the files with a certain name pattern from several folders?

조회 수: 143 (최근 30일)
George
George 2022년 7월 6일
답변: Stephen23 2022년 7월 6일
Hi, I have text files with the same name format that I want to grab from several folders (also with the same name format) all at once (to then compile the text files into one file).
I read on another post that below is the format to grab it but I cannot get it to work:
filePattern = fullfile(myFolder, '**Folder/*')
(to display what I am looking for, I want to grab all of the files with "grab" in them)
All_files -> Folder1 -> no1
-> grab1
-> Folder2 -> no2
-> grab2
-> Folder3 -> no3
-> grab3
Thank you!
  댓글 수: 1
dpb
dpb 2022년 7월 6일
See the example dir "Find Files in Subfolders" that should work ok for your case that is pretty simple pattern.
I find it easier to often dispatch a dir command to the OS where can use the OS switches and more expanded wildcard matching than what the MATLAB dir() implements, particularly with the JPSoftware command replacement that is far more powerful than the MS-supplied tools if one is on Winders...

댓글을 달려면 로그인하십시오.

답변 (2개)

Benjamin Thompson
Benjamin Thompson 2022년 7월 6일
The dir function will work with wildcard characters:
D = dir(fullfile(myFolder, '*grab*'))

Stephen23
Stephen23 2022년 7월 6일
All_files -> Folder1 -> no1
-> grab1
-> Folder2 -> no2
-> grab2
-> Folder3 -> no3
-> grab3
The double asterisk is a wild wildcard which recursively matches any folder names. It is clearly specified in the DIR documentation that "Characters next to a ** wildcard must be file separators", which your code does not do.
Here are two approaches:
P = 'absolute or relative path to All_Files';
S = dir(fullfile(P,'**','grab*')); % recursively match all subfolders
S = dir(fullfile(P,'Folder*','grab*')) % match subfolders named "Folder..."
Note that you should specify the file extension too.

카테고리

Help CenterFile Exchange에서 File Operations에 대해 자세히 알아보기

제품


릴리스

R2022a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by