Find the latest or newest modified file in a folder or directory with Perl
#I’ve worked on and off with Perl, but really want to be more proficient with it. I will do more automation with Perl and will share it here for my reader and as a reference for myself. I just created a Perl tag on this blog.
#Here is one script I cooked out today. It takes a directory / folder name as input, and return the latest or newest modified file. Suggestions welcome!
#use File::Copy;
use File::stat;
$dirname = shift or die “Please provide a directory to search for”;
$timediff=0;
opendir DIR, “$dirname”;
while (defined ($file = readdir(DIR)))
{
if($file ne “.” && $file ne “..”)
{
$diff = time()-stat(”$dirname/$file”)->mtime;
if($timediff == 0)
{
$timediff=$diff;
$newest=$file;
}
if($diff<$timediff)
{
$timediff=$diff;
$newest=$file;
}
}
}
print $newest,”\n”;
#copy(”$dirname/$newest”, “c:/work/$newest”);
Daniel Howard Said,
June 27, 2008 @
You can also use ls -t:
0-13:19 djh@ratchet ~> ls -lt | grep ^- | head -1
-rw-r–r– 1 djh djh 7477585 Mar 30 14:38 djh_wordpress-2008-03-30.sql
Haidong Ji Said,
June 27, 2008 @
That’s really cool: grep for files, and then take the first line, I learned something already!
Google is good, but sometimes a live and breathing expert can cut through the noise and point you to the right direction. Thanks!
The script I wrote was intended primarily for work on Windows. I am digging the here document, along with variable interpolation to generate some cool sql script.
Thanks for sharing!