Doug's MATLAB Video Tutorials

Find newest file in a directory 9

Posted by Doug Hull,

9 CommentsOldest to Newest

@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

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.

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

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

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!

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.

Add A Comment

What is 8 + 10?

Preview: hide

These postings are the author's and don't necessarily represent the opinions of MathWorks.