John Manak
John Manak

Reputation: 13558

List all files in a directory given a regular expression / a set of extensions (Matlab)

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 is:

f = dir(DIR);
f = {f([f.isdir] == 0).name};
result = f(~cellfun(@isempty, regexpi(f, '.*(avi|mp4)')));

However, I wonder if there is a faster and/or cleaner solution to this?

Is is possible to simplify it if instead of a regular expression I have only a list of possible file extensions?

Upvotes: 7

Views: 18878

Answers (3)

My loop variation:

ext = [".doc",".docx",".rtf"];
f = [];
for e = ext
    f = [f;dir(char(strcat('**/*',e)))];
end
f = f([f.isdir] == 0);

Upvotes: 0

Oleg
Oleg

Reputation: 10676

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

Alternative (not recommended)

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.

Upvotes: 14

Shai
Shai

Reputation: 114796

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{:}];

Upvotes: 0

Related Questions