Sorting a directory of txt files.

조회 수: 7 (최근 30일)
Samuel
Samuel 2013년 5월 11일
편집: Stephen23 2021년 4월 18일
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
Samuel
Samuel 2013년 5월 13일
any help?
Stephen23
Stephen23 2016년 2월 22일
편집: Stephen23 2021년 4월 18일
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'

댓글을 달려면 로그인하십시오.

답변 (3개)

Yao Li
Yao Li 2013년 5월 13일
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 2013년 5월 13일
편집: Jan 2013년 5월 13일
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 2016년 2월 22일
편집: Stephen23 2021년 4월 18일
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'

카테고리

Help CenterFile Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by