Clear Filters
Clear Filters

Sorting csv filenames according to date/time

8 views (last 30 days)
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 Comment
Stephen23
Stephen23 on 29 May 2020
Edited: Stephen23 on 29 May 2020
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'

Sign in to comment.

Accepted Answer

Cris LaPierre
Cris LaPierre on 28 May 2020
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…

More Answers (0)

Categories

Find more on Shifting and Sorting Matrices in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!