Sorting a directory of txt files.

2 Ansichten (letzte 30 Tage)
Samuel
Samuel am 11 Mai 2013
Bearbeitet: Stephen23 am 18 Apr. 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 Kommentare
Samuel
Samuel am 13 Mai 2013
any help?
Stephen23
Stephen23 am 22 Feb. 2016
Bearbeitet: Stephen23 am 18 Apr. 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'

Melden Sie sich an, um zu kommentieren.

Antworten (3)

Yao Li
Yao Li am 13 Mai 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 am 13 Mai 2013
Bearbeitet: Jan am 13 Mai 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 am 22 Feb. 2016
Bearbeitet: Stephen23 am 18 Apr. 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'

Kategorien

Mehr zu File Operations finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by