Create an array of file names produced by system('dir /S *.ext')

27 vues (au cours des 30 derniers jours)
bugguts99
bugguts99 le 27 Avr 2011
Commenté : Seung-Goo Kim le 14 Oct 2022
Hi there,
I know that you can search directories and sub-directories to provide a list of file names that meet a particular criteria using the code below:
[status,list]=system('dir /S *.mp3');
My question is: is it possible to create an array from the file names generated this way in order to create a loop for further processing??
Thanks in advance...

Réponse acceptée

Richard Alcock
Richard Alcock le 27 Avr 2011
You can use textscan to split the multiple lines of output from the system command into a cell array.
[status, list] = system( 'dir /B /S *.mp3' );
result = textscan( list, '%s', 'delimiter', '\n' );
fileList = result{1}
Note that I've added /B to the dir command to make the output easier to parse.
  2 commentaires
bugguts99
bugguts99 le 2 Mai 2011
Thanks - works a treat!
franco otaola
franco otaola le 7 Oct 2016
is there any possibility of extract the name without the extension? thanks

Connectez-vous pour commenter.

Plus de réponses (1)

Sven Mesecke
Sven Mesecke le 27 Avr 2011
What's wrong with the MATLAB function 'dir'? You can add wildcards like .mp3 and get a struct array in return, whose name field can easily be converted into a cell array of filenames:
a=dir('S/*.ext');
b={a.name}
Otherwise there's a nice tool on MATLAB Central that uses regular expressions for dir: http://www.mathworks.com/matlabcentral/fileexchange/16216-regexpdir
  5 commentaires
nvmnghia
nvmnghia le 23 Fév 2020
Why can't we use
b = [a.name]
here?
Seung-Goo Kim
Seung-Goo Kim le 14 Oct 2022
@nvmnghia you can try it yourself on your computer. But now MATLAB supports something like Jupyter notebook on a virtual environment:
pwd
ans = '/users/mss.system.TC8Vlw'
unix('echo"" > thisfile1.txt'); unix('echo"" > ThatFile-1234.txt');
a = dir('*.txt')
a = 2×1 struct array with fields:
name folder date bytes isdir datenum
b = [a.name]
b = 'ThatFile-1234.txtthisfile1.txt'
This will create a very wide character array by horizontally concatenating cated character arrays (i.e., file names). Then it becomes another problem to access each file. You usually can't do vertical concatenation because often the file names have different number of characters.
b = cat(1,a.name)
Error using cat
Dimensions of arrays being concatenated are not consistent.
So, this is why you want to cast them into a cell array, instead of a character array, as @Sven Mesecke wrote above.

Connectez-vous pour commenter.

Catégories

En savoir plus sur File Operations dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by