Check the existence of a directory based on part of a string?

19 visualizzazioni (ultimi 30 giorni)
hello all,
I have a range of sub-folders which are named as CL_CS, CL_CS_01, CL_CS_02...CL_CS_xx. These folders are located in same directory with other folders. I want to run a loop which checks the first 5 characters of the folder name and run some operations inside those folders.
I am not quite sure how to match the string for a folder name. So far...
fpath = 'CL_CS';
while isequal(exist(fpath,'dir'),7)
% do something here
end
Thanks!

Risposta accettata

Stephen23
Stephen23 il 24 Ago 2016
Modificato: Stephen23 il 18 Apr 2021
The simplest option is to use dir directly to return only directory names that match that pattern.
You might also want to sort those directory names using my FEX submission natsortfiles.
S = dir('CL_CS*');
S = S([S.isdir]);
S = natsortfiles(S); % (optional) alphanumeric sort by filename
and then simply loop over those subdirectory names:
for k = 1:numel(S)
name = S(k).name
... your code
end
  2 Commenti
automycer
automycer il 24 Ago 2016
This works great. Thanks! I had an issue with concatenating the directory path for my CL_CS folder in the dir function (since everything is defined in nested structures), but the asterisk(*) is a life saver.
Also, I will be needing natsortfiles later on. Thanks for that too!
Stephen23
Stephen23 il 24 Ago 2016
Modificato: Stephen23 il 18 Apr 2021
Use fullfile to join the path string to the name pattern string:
S = dir(fullfile(pathStr,'CL_CS*'));
and then also inside the loop:
name = fullfile(pathStr,S(k).name)

Accedi per commentare.

Più risposte (1)

Azzi Abdelmalek
Azzi Abdelmalek il 24 Ago 2016
When you run
f=dir(current_folder)
You wil get a cell array of the content of your current folder, like
f={'CL_CS','CL_CS_01','CL_CS_02','other1' 'other'}
name=regexp(f,'CL_CS.+','match','once')
idx=~cellfun(@isempty,name)
name=name(idx)
  4 Commenti
Stephen23
Stephen23 il 24 Ago 2016
Modificato: Stephen23 il 24 Ago 2016
@automycer: see my answer, I already showed you how to do this correctly (Azzi Abdelmalek's answer is not correct, because as you have found dir returns a structure, not a cell array of names).
And I also showed you how to get the names into the correct order!
Azzi Abdelmalek
Azzi Abdelmalek il 24 Ago 2016
@Stephen Cobeldick, why the answer is not correct? dir returns a struct variable, but you can get the cell array containing the names, as mentioned in my above comment!

Accedi per commentare.

Categorie

Scopri di più su Search Path in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by