필터 지우기
필터 지우기

Need an Elegant Sorting Solution for Directory File Names

조회 수: 1 (최근 30일)
John Cruce
John Cruce 2023년 7월 9일
편집: Voss 2023년 7월 9일
I have a directory of filenames, (within a files structure array) structured like this:
cdef2.20140101.pdef.txt
cdef2.20140102.pdef.txt
....
pdef.gdef.201300101-20130105.txt
pdef.gdef.201300106-20130110.txt
....
I need to reorder these (ascending order from oldest to newest) according to the dates embedded within these file names which are formatted like YYYYMMDD. I've explored several options, but I'm seeking an elegant solution without do loops. Any tips or suggestions would be appreciated.
  댓글 수: 3
John Cruce
John Cruce 2023년 7월 9일
Needing to sort by the first date in pdef.gdef.201300101-20130105.txt (i.e., 20130101). I considered running a shell script to rename the files but trying not to add another step.
Sandeep Mishra
Sandeep Mishra 2023년 7월 9일
Can we assume that there exist only two type of files?
One which starts with cdef2 and one which starts with pdef?

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

채택된 답변

Voss
Voss 2023년 7월 9일
편집: Voss 2023년 7월 9일
filenames = { ...
'cdef2.20140101.pdef.txt'; ...
'cdef2.20140102.pdef.txt'; ...
'pdef.gdef.20130101-20130105.txt'; ...
'pdef.gdef.20130106-20130110.txt'}
filenames = 4×1 cell array
{'cdef2.20140101.pdef.txt' } {'cdef2.20140102.pdef.txt' } {'pdef.gdef.20130101-20130105.txt'} {'pdef.gdef.20130106-20130110.txt'}
dates = regexp(filenames,'\d{8}','match','once');
[~,idx] = sort(dates);
sorted_filenames = filenames(idx)
sorted_filenames = 4×1 cell array
{'pdef.gdef.20130101-20130105.txt'} {'pdef.gdef.20130106-20130110.txt'} {'cdef2.20140101.pdef.txt' } {'cdef2.20140102.pdef.txt' }

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 File Operations에 대해 자세히 알아보기

제품


릴리스

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by