Tuesday, November 17, 2009

Find Files Created Between 2 Times

In order to find files created between two times (start hour and end hour). The required hours are hours from current time. For example,

Current time = 2 PM = 14:00

If you want file created between 9 AM and 12 PM today, the start hour and end hour are:

Start Hour = (14 - 9) = 5
End Hour = (14 - 12) = 2

Hence required command is:


$ ./find_files_between_times.pl /path/to/dir 5 2



The Perl script which does this is given below:-


#!/usr/bin/perl -w
#===============================================================================
#
# FILE: find_files_between_times.pl
#
# USAGE: ./find_files_between_times.pl <dir> <start_hour> <end_hour>
#
# DESCRIPTION:
#
# OPTIONS: ---
# REQUIREMENTS: ---
# BUGS: ---
# NOTES: ---
# AUTHOR: Mitesh Singh Jat (mitesh), <mitesh[at]yahoo-inc[dot]com>
# COMPANY: Yahoo Inc, India
# VERSION: 1.0
# CREATED: 11/13/2009 10:00:02 PM IST
# REVISION: ---
#===============================================================================

use strict;
use warnings;

if (@ARGV != 3)
{
print STDERR "Usage: $0 <dir> <start_hour> <end_hour>\n";
exit(-1);
}

my $dir = $ARGV[0];
## Calculate current_hour - given_hour
#my $start_time = `/bin/date "+\%H"`;
my $start_time = $ARGV[1];
#chomp($start_time);
my $end_time = $ARGV[2];
$end_time = time - ($end_time * 60 * 60);
#$end_time = $start_time - $end_time;
#$start_time = $start_time - $ARGV[0];

if ($start_time > $end_time)
{
($start_time, $end_time) = ($end_time, $start_time);
}

my $cmd = "find $dir -ctime -$start_time";
print "Running $cmd\n";
my @files = `$cmd`;
foreach my $file (@files) # (`find $dir -ctime $start_time`)
{
chomp($file);
my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
$atime,$mtime,$ctime,$blksize,$blocks)
= stat($file);

if ($ctime > $end_time)
{
next;
}
print "$file\n";
}


exit(0);


No comments: