Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Shaun E on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Proper Way To Use Grep?

Status
Not open for further replies.

StormMedic85

Programmer
Sep 7, 2007
20
US
Within an array of files, I'd like to search for files with a specific pattern. All the files follow a standard format (for example, abc123.YEAR.MONTH.DAY.abc.TIME). I'm trying to use grep but I think my implementation may be incorrect. Here's an example of how I'm trying to do things. Perhaps it'll be easy to see where I'm going wrong. Thanks!

$dirname = "/directory";
opendir(FH, $dirname);
while (defined($file = readdir(FH))) {
@filearray = "$dirname/$file";
}

@filematch = grep(/abc123.$year$month$day.abc.$time/, @filearray);

print "The matched files are @filematch";
 
What's contained in the $year, $month, $day and $time variables?
 
Two culprits:

1:

Code:
while (defined($file = readdir(FH))) {
    [b]@filearray = "$dirname/$file";[/b]
}

You need to be adding to the array...

Code:
while (defined($file = readdir(FH))) {
    [b]push @filearray, "$dirname/$file";[/b]
}

2: Your regex should have the periods escaped

/abc123\.$year$month$day\.abc\.$time/
 
BTW, you probably don't even need grep() for this level of matching.
glob() should be enough.

Code:
print join "\n", glob( "$dirname/abc123.$year$month$day.abc.$time" );

 
If the user is supplying the exact date and time, then there isn't any pattern to match, as far as I can see. If you have the date and time, you also have the full filename, no?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top