Sorting csv filenames according to date/time

8 次查看(过去 30 天)
Hello,
I have the following csv files in a directory:
'Screen 5_05-06-2020_03-19-18-PM.log.csv'
'Screen 5_05-06-2020_04-17-22-PM.log.csv'
'Screen 5_05-06-2020_11-03-19-AM.log.csv'
'Screen 5_05-06-2020_11-06-22-AM.log.csv'
'Screen 5_05-06-2020_11-45-15-AM.log.csv'
I am trying to concatenate them but Matlab messes up the order, I've tried using the natsort function but it is not giving me the right result. How can I sort it so that the result is this:
'Screen 5_05-06-2020_11-03-19-AM.log.csv'
'Screen 5_05-06-2020_11-06-22-AM.log.csv'
'Screen 5_05-06-2020_11-45-15-AM.log.csv'
'Screen 5_05-06-2020_03-19-18-PM.log.csv'
'Screen 5_05-06-2020_04-17-22-PM.log.csv'
  1 个评论
Stephen23
Stephen23 2020-5-29
编辑:Stephen23 2020-5-29
Note that if the filenames used ISO 8601 formats then a basic character sort would return them in chronological order:
Note only that, but most OSs would also display them in chronological order. Better names:
'Screen 5_2020-06-05_11-03-19.log.csv'
'Screen 5_2020-06-05_11-06-22.log.csv'
'Screen 5_2020-06-05_11-45-15.log.csv'
'Screen 5_2020-06-05_15-19-18.log.csv'
'Screen 5_2020-06-05_16-17-22.log.csv'

请先登录,再进行评论。

采纳的回答

Cris LaPierre
Cris LaPierre 2020-5-28
The way I can think to do this is to extract the date and time text from the filename, convert it to a datetime, sort the datetime array, and use the index from sort to reorder the files.
files = {'Screen 5_05-06-2020_03-19-18-PM.log.csv'
'Screen 5_05-06-2020_04-17-22-PM.log.csv'
'Screen 5_05-06-2020_11-03-19-AM.log.csv'
'Screen 5_05-06-2020_11-06-22-AM.log.csv'
'Screen 5_05-06-2020_11-45-15-AM.log.csv'};
% extract date and time
date = extractBetween(files,"Screen 5_",".log");
% Convert to datetime array
date = datetime(date,"InputFormat","dd-MM-yyyy_hh-mm-ss-a");
% sort datetimes in ascending order
[~,ind] = sort(date);
% reorder original filenames using sort order
files = files(ind)
files = 5×1 cell array
'Screen 5_05-06-2020_11-03-1…
'Screen 5_05-06-2020_11-06-2…
'Screen 5_05-06-2020_11-45-1…
'Screen 5_05-06-2020_03-19-1…
'Screen 5_05-06-2020_04-17-2…

更多回答(0 个)

类别

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