Sorting csv filenames according to date/time

10 visualizaciones (últimos 30 días)
Sridutt Gokul
Sridutt Gokul el 28 de Mayo de 2020
Editada: Stephen23 el 29 de Mayo de 2020
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 comentario
Stephen23
Stephen23 el 29 de Mayo de 2020
Editada: Stephen23 el 29 de Mayo de 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'

Iniciar sesión para comentar.

Respuesta aceptada

Cris LaPierre
Cris LaPierre el 28 de Mayo de 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…

Más respuestas (0)

Categorías

Más información sobre Shifting and Sorting Matrices en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by