Samer
Samer

Reputation: 1980

MATLAB extract files with certain extension from a folder

How to extract all the files with certain extension giving the name of the directory and the extension without changing the current directory?

I have looked into dir but this only search current directory and its subfolders, it does not take a certain directory as an argument. Same thing with ls command. My MATLAB info is a bit rusty. Thanks.

Upvotes: 0

Views: 1580

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112669

You can specify a folder and an extension in dir as follows. Let

folder = 'c:\users\Luis';
extension = 'txt';

Search in a folder

To display the results on screen:

dir([folder filesep '*.' extension])

To obtain a cell array of strings with the matching file names:

d = dir([folder filesep '*.' extension]);
filenames = {d.name};

Search in a folder and subfolders recursively

According to the documentation, use a double wildcard:

dir([folder filesep '**' filesep '*.' extension])

or

d = dir([folder filesep '**' filesep '*.' extension]);
filenames = {d.name};

Upvotes: 2

Related Questions