Search code examples
regexperlfilematchglob

Extract portion of filename with Regex in Perl


I have a directory of files in the file system:

111111.222.log
222222.33.log
444444.0.log

If I have access to a variable $id, where $id is the first part of numbers before the first ., how do I get the second part of the number?

$id is a known value, the $unknown second part of the number is what I want to extract from the filename if it exists.

Is there some efficient approach to get this done without saving the entire directory of files into array, then go through each element with split?

What I have in mind is something like:

if (-e '$id.(\d+).log') {
    $unknown = $1;
}

The above is not a valid code, just an idea.

In reverse, if I have access to the full string, the regex I'm using for the extraction is (where 22 is $unknown):

"158855.22.log" =~ /^(\d+)\.(\d+)\.log$/;
print "ID is $1\n";
print "Unknown is $2\n";

Solution

  • You can combine glob with regex matching:

    foreach my $filename (glob "$id.*.log")
    {
        if ($filename =~ /^(\d+)\.(\d+)\.log$/)
        {
            print "ID is $1\n";
            print "Unknown is $2\n";
        }
    }