How to scan directories and find a specific file in each folder and their respective subfolders

조회 수: 45 (최근 30일)
My folder structure contains a main folder and few sub folders in them and those sub folders contain a specific file (bkg.txt) in them. I want MATLAB to go into one folder and find that file, and come out of that folder and enter the next directory and find the file in that folder. Can I have a loop for that?
  댓글 수: 1
Stephen23
Stephen23 2022년 1월 3일
편집: Stephen23 2022년 1월 3일
Of course, you can simply use the DIR ** syntax:
P = 'absolute/relative path to the main directory';
S = dir(fullfile(P,'**','bkg.txt'))
and then loop over the structure array S.

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

채택된 답변

dpb
dpb 2022년 1월 3일
편집: dpb 2022년 1월 3일
Of course.
However, with base MATLAB syntax you have to traverse the folder tree manually/explicitly in code; there are a number of FEX submissions to do this in various ways; one very handy one is an extension of the idea of arrayfun to filefun to apply the same function to files in a folder or set of subfolders. It hides all the work under the hood for you.
Alternatively, if I'm searching for a specific file as you are in the problem description, I'll generally just pass the directory search of to the OS that can do the subdirectory search and return the list directly -- with Windoes your specific search looks like
[~,fn]=system("dir /b /s bkg.txt")
for i=1:numel(fn)
% process each fn(i) here...
...
end
Why oh why, TMW won't build the facility into dir() to allow the OS switches associated with the native directory search command is beyond ken...it's another I poked on for 10 year or more and finally just gave up as lost cause.
  댓글 수: 2
Stephen23
Stephen23 2022년 1월 3일
"However, with base MATLAB syntax you have to traverse the folder tree manually/explicitly in code"
Or you can simply use **
dpb
dpb 2022년 1월 3일
Huh. If I had ever known that, surely had forgotten it. Thanks for the note...that is, indeed, of great help.

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

추가 답변 (0개)

카테고리

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

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by