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

Im trying to get a list of files with certain filename using grep. I've read the doc on grep, just can't get the expression right. Here's what I have:
my $search_string = "C04*".substr($year, 2, 2).$month.$day."*.ORD_API" +; my $dir = "C:\\done\\"; my $file; my $i; opendir DIR, $dir; my @file = grep {!/^$search_string/} readdir DIR; closedir DIR; foreach $file(@file){ print $dir.$file[$i]."\n"; $i++; }
An example of a filename that I want is:
C04SHP04071500098417.ORD_API
The problem is I'm getting all files in the directory I'm searching. Thanks for any help.

Replies are listed 'Best First'.
Re: Help with grep
by Art_XIV (Hermit) on Jul 16, 2004 at 17:38 UTC

    Keep an eye on the asterisks that you are putting in $search_string, too. An asterisk means 'match the preceeding element 0 or more times, so the asterisk in 'C04*' means 'match the digit 4 zero or more times'.

    An asterisk in 'C04\w*' would mean 'match any alphanumeric character (or underscore) zero or more times.

    Hanlon's Razor - "Never attribute to malice that which can be adequately explained by stupidity"
      Thanks Art! This did it:
      my $search_string = 'C04\w*'.substr($year, 2, 2).$mon.$day.'\w*.ORD_AP +I'; my $dir = 'C:\\done\\'; my $file; my $i; opendir DIR, $dir; my @file = grep {/^$search_string/} readdir DIR; closedir DIR; foreach $file(@file){ print $dir.$file[$i]."\n"; $i++; }
Re: Help with grep
by keszler (Priest) on Jul 16, 2004 at 17:43 UTC
    Your $search_string would look something like:

    "C04*040716*.ORD_API"
    i.e. look for "C0", 0 or more "4"s, "04071", 0 or more "6"s, any single character ("."), then "ORD_API".

    What you probably need is something like:

    my $search_string = "C04.*?".substr($year,2,2).$month.$day.".*\.ORD_AP +I";
    Try perlre. "regex" is short for Regular Expression.
Re: Help with grep
by eric256 (Parson) on Jul 16, 2004 at 17:27 UTC

    The ! tells you it want all files that DON't match the $search_string. Try it without that and see if you have any luck. If not its probably something todo with your regex. Try hand codeing the regex first, then work on creating it dynamicaly.


    ___________
    Eric Hodges
      Of course... The "!" means not, sorry. I tried without and it returned nothing at all. I am new to perl, so when you talk of the regex, what do you mean?