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

后端 未结 3 1443
花落未央
花落未央 2020-12-06 07:28

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

相关标签:
3条回答
  • 2020-12-06 07:59

    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.

    0 讨论(0)
  • 2020-12-06 08:00

    My loop variation:

    ext = [".doc",".docx",".rtf"];
    f = [];
    for e = ext
        f = [f;dir(char(strcat('**/*',e)))];
    end
    f = f([f.isdir] == 0);
    
    0 讨论(0)
  • 2020-12-06 08:07

    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{:}];
    
    0 讨论(0)
提交回复
热议问题