bh_perl has asked for the wisdom of the Perl Monks concerning the following question:

Hi..

ANybody knows how to capture or grep all files in input directory based on date ?.

As example, I want to read all yesterday file from input directory only.

Thank you
  • Comment on How to read list of files based on date ?

Replies are listed 'Best First'.
Re: How to read list of files based on date ?
by 1Nf3 (Pilgrim) on May 22, 2009 at 07:55 UTC

    Use the -M test operator. It returns the age of a file in days, so, for example, if you want to process only files from yesterday, the code could look like this: (untested)

    foreach my $file (@filelist) { if ( int( -M $file ) < 1 ) { # do something with a file } }

    int () is used because -M returns values like 0.50 when a file is less than a day old.

    If you want to perform a specific task, please tell what you want to do with the files, I'll be glad to write some example code.

    Update:

    As Utilitarian was kind enough to suggest, readdir works just fine. However, I would try using File::Find, its both simple and powerful, in case you'll need some extra functionality later on. Here's an example of it's use: (this time it's tested ;] )

    #!/usr/bin/perl -w use strict; use File::Find; my $directory = "d:/usr"; print "List of files newer than yesterday in $directory:\n"; find(\&process, $directory); sub process { if ((int(-M) < 1) && (-f)) { print " $File::Find::name\n"; } }

    Output:

    List of files newer than yesterday in d:/usr: d:/usr/newfile1.txt d:/usr/newfile2.txt

    The -f file test operator ensures we process only files, normally the output would contain d:/usr too. The process sub is executed for every file found in a directory, so feel free to modify it for your own needs.

    Rgards,
    Luke

Re: How to read list of files based on date ?
by Utilitarian (Vicar) on May 22, 2009 at 07:57 UTC
    You can get the names of every file in a directory with the readdir command
    opendir (DIR,"./"); @files = readdir DIR;
    And the stat command gives you access to the details of a file
    foreach $file (@files){ if ( -f $file){ my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime, +$blksize,$blocks)= stat($file); push (@wanted) $file if ((time() - $mtime) < (24*60*60); } }
      Instead of stat() and calculating the age in days yourself, that is returned by the -M operator.
      my @wanted = grep -f $_ && -M _ < 1, @files;
      or something close to that.