I have a regular expression defining the filenames of interest. What is the best way to list all files in a directory that match this condition?
My attempt at this i
Fundamentally your approach is what I would go for. However, your lines of code can be simplified to (directories are lost in the regex and empty cells in the final concatenation):
f = dir('C:\directory');
f = regexpi({f.name},'.*txt|.*pdf','match');
f = [f{:}];
Also, note that the function dir()
accepts wildcards (*
) but not multiple extensions:
dir('C:\directory\*.avi')
This means you can retrieve immediately only those files that match an extension, however you have to loop for the number of extensions:
d = 'C:\users\oleg\desktop';
ext = {'*.txt','*.pdf'};
f = [];
for e = 1:numel(ext)
f = [f; dir(fullfile(d,ext{e}))];
end
ext = {'*.txt','*.pdf'};
str = ['!dir ' sprintf('%s ',ext{:}) '/B'];
textscan(evalc(str),'%s','Delimiter','')
where str
is !dir *.txt *.pdf /B
and evalc()
captures the evaluation of the string and textscan()
parses it.
My loop variation:
ext = [".doc",".docx",".rtf"];
f = [];
for e = ext
f = [f;dir(char(strcat('**/*',e)))];
end
f = f([f.isdir] == 0);
Suppose you have a cell array with possible extensions, e.g., exts = {'avi','mp4'}
. Then you can do the following
f = cellfun( @(x) dir( fullfile( DIR, ['*.',x] ) ), exts, 'UniformOuput', false );
result = [f{:}];