reaaranging filesnames
Show older comments
Dear Matlabians.
I have build 2 scripts that are taking multiples xls files and and collecting data and make a final xls files.
The name of the initial files are consistent but are faulty.
The names look like. Vela2_DayMonthYear_NumberofTest_Car_TypeofFile
e.g. Vela2_01032011_001_Audi4_BAG, Vela2_01032011_002_Audi4_BAG, Vela2_25022011_001_Audi4_BAG, Vela2_25022011_002_Audi4_BAG, Vela2_28022011_001_Audi4_BAG, Vela2_28022011_002_Audi4_BAG
As my script is build and matlab is build it takes first 01032011_001 then 01032011_002 then 25022011_001 then 25022011_002 and then 28022011_001 and finally 28022011_002. This is not correct.
I want to take firstly 25022011_001 then 25022011_002 then 28022011_001 then 28022011_002 and finally 01032011_001 and 01032011_002 .
Normally people that name files should put the year then the month and then the day to name files. Put know things are wrong and I have to find a solution. I was thinking in producing a list inside my script that will take the name of the files rearrange the files by YearMonthDay_NumberofTest and link to the old files and use that. But I don't have any idea if this is a good idea or if there is a better way in doing this.
Any help will be very nice Thank you very much
Accepted Answer
More Answers (1)
David Young
on 6 Dec 2011
You can sort the filenames into the order you require like this.
First, all the filenames need to be a cell array. Their order does not matter.
filenames = { ...
'Vela2_01032011_001_Audi4_BAG'...
'Vela2_01032011_002_Audi4_BAG'...
'Vela2_25022011_001_Audi4_BAG'...
'Vela2_25022011_002_Audi4_BAG'...
'Vela2_28022011_001_Audi4_BAG'...
'Vela2_28022011_002_Audi4_BAG'};
Then you sort them by changing the names to the year/month/day ordering and calling sort. If the names don't all start 'Vela2_' you can omit it from the pattern.
tempnames = regexprep(filenames, 'Vela2_(\d\d)(\d\d)(\d\d\d\d)', 'Vela2_$3$2$1');
[~, ind] = sort(tempnames);
sortnames = filenames(ind);
Now newnames has the original filenames, but in the correct order, as we can demonstate by printing them out:
for ii = 1:length(sortnames)
disp(sortnames{ii});
end
which prints
Vela2_25022011_001_Audi4_BAG
Vela2_25022011_002_Audi4_BAG
Vela2_28022011_001_Audi4_BAG
Vela2_28022011_002_Audi4_BAG
Vela2_01032011_001_Audi4_BAG
Vela2_01032011_002_Audi4_BAG
If you use a loop to iterate over sortnames, you'll process them in date order.
2 Comments
Alexandros
on 7 Dec 2011
David Young
on 7 Dec 2011
See my comment on your answer. ind is just a variable: to understand its role, look at the documentation for the sort() function.
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!