Click to See Complete Forum and Search --> : Need to grep, when found get timestamp of file - HELP


Phill Pafford
09-20-2006, 03:10 PM
Ok, I need help writing a perl script to grep a large set of number (Over 11,000) when of if found the I need to output to a file the zipfile it was found in and the timestamp of that file.

There are many subdirectories in the main directory and each directory has some files in it, im looknig to match one of the number from my list. When it finds a match, output the zip file name and the timestamp to a log file. Then move to the next number to grep but start from the main directory again.

I have never attempted to do something this size and wanted to know if there was a script allready made or maybe some code to head me in the right direction.

Phill Pafford
09-21-2006, 03:52 PM
not alot of help in the perl section of this site, use to the php forum where I can get help within a 24 hour period.

Again I found the answer to my own question, here are the results:
(This will look in all the directories from the directory you give as the parameter)


#!/usr/bin/perl

# Declare the subroutines
sub trim($);

# Perl trim function to remove whitespace from the start and end of the string
sub trim($)
{
my $string = shift;
$string =~ s/^\s+//;
$string =~ s/\s+$//;
return $string;
}

# open file
open(FILE, "YOUR_PARAMETER_FILE_WITH_THE_NAMES_OF_THE_FILES_YOUR_SEARCHING_4") or die("Unable to open file");

# read file into an array
@data = <FILE>;

# close file
close(FILE);

# print file contents
foreach $line (@data)
{
$name_of_file = trim($line);

use File::Find;

my $dir_name = '/THE/PATH/OF/YOUR/DIRECTORY/';

find(
sub {
if(/$name_of_file/i && -f) {do_this($_);}
}, $dir_name
);

sub do_this {

#Set File
$file = "$_";

#Get Timestamp
use File::stat;
use Time::localtime;
$date_string = ctime(stat($file)->mtime);

# define hash
%file_found = ('file_name' => $file, 'Timestamp' => $date_string);

# retrieve value of hash element
$name = $file_found{'file_name'};
$time = $file_found{'Timestamp'};

#if you want to see your files print to the screen as well
#un comment the next line
#print ("$time - $name\n");

$found_one = "$time - $name\n";
open (backup, ">>/PATH/TO/YOUR/LOG/FILE/log.txt") || die ("Could not open file. $!");
print backup ($found_one);
close (backup);

}

}