Stuart’s MATLAB Videos

Watch and Learn

Find newest file in a directory 9

Posted by Doug Hull,

9 CommentsOldest to Newest

dhull replied on : 2 of 9
@Kevin, Thank you, as with many of my videos the intent is more to take a simple example to show general techniques. This command does solve this specific problem very nicely though. Thanks, Doug
Vishu replied on : 3 of 9
Excellent. This was of a great help to me because i have to read files with stamp. However, one small correction. In line 5, replace the '~' with some variable eg. a. What kevin wrote was right though i cudn get how to obtain the latest file name.
Dominik replied on : 5 of 9
Hi, Neat trick getting the max of datenum. I would like to find the newest folder in my current directory so that I can rename it. I have a folder full of .zip files, I want to one at a time, rename the directory that it creates and then move on to the next .zip. If you do after unzip it includes . and .. as directories that are newer than anything else. Since I don't have an extension to separate with, how can I differentiate between ., .., and actual folders? Thanks
Dominik replied on : 6 of 9
Sorry, that didn't come out as I wanted above: Neat trick getting the max of datenum. I would like to find the newest folder in my current directory so that I can rename it. I have a folder full of .zip files, I want to unzip one at a time, rename the directory that it creates and then move on to the next .zip. If you do dir after unzip it includes . and .. (and sometimes .DS_Store which I think gets created after unzipping) as files/directories that are newer than anything else. Since I don’t have an extension to separate with, how can I differentiate between ., ..,.DS_Store and actual folders? Some code I have that is a bit of a hack and the last line doesn't work because you can dynamically reference(?) inside the unix command: files=dir; for i=3:length(files) unzip(files(i).name); fd=dir; for j=1:length(fd) dn=[fd(4:end).datenum]; [~,newestI]=max(dn); [~,nom,~]=fileparts(files(i).name); old=fd(newestI+3).name; unix('mv old nom') end end
Dominik replied on : 7 of 9
I figured out my problem doing: files=dir('*.zip'); for i=3:length(files) [~,nom,~]=fileparts(files(i).name); unzip(files(i).name,nom); fd=dir(nom); cd(nom) cd(fd(end).name) unix('mv * ../') cd ../ rmdir(fd(end).name) cd ../ end but I would still be curious if there is a way to not capture the . and .. in the dir command. Or more broadly, dir everything except . which could also be applied to everything but .jpg etc. Thanks!
Leslie replied on : 8 of 9
How would this code change if I wanted to find only the newest files since the last run of this code?
Doug replied on : 9 of 9
There is a date field that comes out of the command also. You would parse that. You might need to store the last run data in a file on disk somewhere.