Sorting a directory of txt files.

2 visualizaciones (últimos 30 días)
Samuel
Samuel el 11 de Mayo de 2013
Editada: Stephen23 el 18 de Abr. de 2021
Hello, I am trying to sort out a list of txt files I have in a certain directory, so they can be loaded in order one at a time. For example, in my directory are a numerically ordered list of txt files: 800.txt,900.txt,1000.txt,1200.txt,total.txt,etc.
I want to load just the number files in ascending order. I noticed that just using the ls command directory will sort out by the first numerical digit, not taking account of the digits, and therefore not making it truly numerically ascending.
Here is the portion of the code I am running:
cd('c:\directory');
list=ls('*.txt')
%this is the routine to load the txt file itself. in example, the fifth file.
y=load(list(5,:));
I read up on this article involving the ASCII ascending and how a separate routine needs to be separately written to manually ascend it. However, this method will involve the creation of a cell array, and the load command didn't work on the file list generated: http://www.mathworks.com/support/solutions/en/data/1-OGU22/index.html?product=ML
Any help involving this problem will be appreciated. Thanks
  2 comentarios
Samuel
Samuel el 13 de Mayo de 2013
any help?
Stephen23
Stephen23 el 22 de Feb. de 2016
Editada: Stephen23 el 18 de Abr. de 2021
My FEX submission natsortfiles was written to deal with this exact problem:
>> S = dir('*.txt');
>> S.name
ans =
'1.txt'
ans =
'10.txt'
ans =
'2.txt'
>> S = natsortfiles(S); % alphanumeric sort by filename
>> S.name
ans =
'1.txt'
ans =
'2.txt'
ans =
'10.txt'

Iniciar sesión para comentar.

Respuestas (3)

Yao Li
Yao Li el 13 de Mayo de 2013
Implement dir to list all the file names in the specific directory.
Use if-else to find the number files (char(48) to char(57))
Implement sort(xxx,'ascend') to sort the elements in ascending order

Jan
Jan el 13 de Mayo de 2013
Editada: Jan el 13 de Mayo de 2013
list = dir(fullfile(C:\directory', '*.txt'));
list = list(~[list.isdir]); % Exclude folder with matching name
name = {list.name};
str = sprintf(name, '%s*');
num = sscanf(str, '%d*');
[dummy, index] = sort(num);
name = name(index); % Sorted numerically now
for iName = 1:length(name)
y = load(name{iName});
...
end

Stephen23
Stephen23 el 22 de Feb. de 2016
Editada: Stephen23 el 18 de Abr. de 2021
My FEX submission natsortfiles was written to deal with this exact problem:
>> S = dir('*.txt');
>> S.name
ans =
'1.txt'
ans =
'10.txt'
ans =
'2.txt'
>> S = natsortfiles(S); % alphanumeric sort by filename
>> S.name
ans =
'1.txt'
ans =
'2.txt'
ans =
'10.txt'

Categorías

Más información sobre File Operations en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by