Effacer les filtres
Effacer les filtres

Sorting csv filenames according to date/time

8 vues (au cours des 30 derniers jours)
Sridutt Gokul
Sridutt Gokul le 28 Mai 2020
Modifié(e) : Stephen23 le 29 Mai 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 commentaire
Stephen23
Stephen23 le 29 Mai 2020
Modifié(e) : Stephen23 le 29 Mai 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'

Connectez-vous pour commenter.

Réponse acceptée

Cris LaPierre
Cris LaPierre le 28 Mai 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…
  1 commentaire
Sridutt Gokul
Sridutt Gokul le 29 Mai 2020
Thank you, this worked flawlessly for me!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Shifting and Sorting Matrices dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by