List of all files in the directory specified by the regular expression / set of extensions (Matlab)

I have a regular expression defining the file names of interest. What is the best way to list all the files in a directory that match this condition?

My attempt:

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?

Is it possible to simplify it if, instead of the usual expression, I only have a list of possible file extensions?

+6
source share
3 answers

In essence, your approach is what I would go for. However, your lines of code can be simplified (directories are lost in the regular expression and empty cells in the final concatenation):

 f = dir('C:\directory'); f = regexpi({f.name},'.*txt|.*pdf','match'); f = [f{:}]; 

Also note that the dir() function accepts wildcards ( * ), but not several extensions:

 dir('C:\directory\*.avi') 

This means that you can immediately get only those files that correspond to the extension, however, a number of extensions requires a loop :

 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 !dir *.txt *.pdf /B and evalc() captures the line score, and textscan() parses it.

+12
source

Suppose you have an array of cells with possible extensions, for example, exts = {'avi','mp4'} . Then you can do the following

 f = cellfun( @(x) dir( fullfile( DIR, ['*.',x] ) ), exts, 'UniformOuput', false ); result = [f{:}]; 
0
source

My loop change:

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

Source: https://habr.com/ru/post/945842/


All Articles