Zesa Rex Zesa Rex - 2 months ago 10
Perl Question

How can I let grep scan only the first 12 characters in filename?

I am trying to filter files by their filename.

You are asked to input two dates, then my code goes through all files and writes all files fitting to the search parameters into an array.

But if I input an inaccurate range like 2014 .. 2016, it happens that files that are not relevant to my search (as I want to grep only the first 8 characters as those represent a datestamp) like the first two files in

@files
are also filtered because they contain 2014, 2015 or 2016 elsewhere in their name.

@files = 20120830_600020143_1_Log.csv (wrong because year 2012)
20130830_600020161_1_Log.csv (wrong because year 2013)
20150830_600020162_1_Log.csv
20160830_600020121_1_Log.csv


How can I grep only the the first 12 characters of a filename?

I thought of a mix with
substr
but couldn't get it to work.

Here's the code I need to change. In this case
$daterange
is
"2016"


foreach $folder ( @folder ) {

$curdir = "$scriptdir\\$folder";

opendir my $dir_b, "$curdir" or die "Can't open directory: $!";
my @files = grep { /$daterange/ } readdir $dir_b;
closedir $dir_b;

foreach $files ( @files ) {
...
}

Answer

It sounds like you want to search only the first eight characters of each file name. That would look like this

my @files = grep { substr($_, 0, 8) =~ $daterange } readdir $dir_b;

I would prefer to use readdir in a while loop, like this

foreach $folder ( @folder ) {

    my $curdir = "$scriptdir\\$folder";

    opendir my $dh, $curdir or die qq{Unable to open directory "$curdir": $!};

    while ( my $node = readdir $dh ) {

        next if $node eq '.' or $node eq '..';
        next unless substr($node, 0, 8) =~ $daterange;

        my $fn = "$curdir\\$node";
        next unless -f $fn;

        # Do stuff with $fn
    }
}
Comments