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

Hi. I have log file names in below format

1) apachelog_LT100.7.7.7_21.SRV.apache.20161130-123456.258976.log

2) APACHE_PP1.20161130-12:39:55-30822.Release.LT100.7.7.7.PP1.log

3) APACHE_PS_PP1.20161130-15:29:37-5319.ebf_run.LT100.7.7.7.log

Need to store the date 20161130 in one variable for all files separately, How do I create the regular expression for this. Thanks.

  • Comment on Extracting datapart (YYYYMMDD) with filename regular expression

Replies are listed 'Best First'.
Re: Extracting datapart (YYYYMMDD) with filename regular expression
by stevieb (Canon) on Dec 01, 2016 at 15:47 UTC

    Hi rahulme81, please show us what you've tried so far. You've been asked to do this before. We prefer to help people with specific problems so they can learn as opposed to outright doing their work for them (which inevitably leads to future questions on the exact same topic).

    You can peruse the regex quick intro, the tutorial or the documentation.

Re: Extracting datapart (YYYYMMDD) with filename regular expression
by Laurent_R (Canon) on Dec 01, 2016 at 23:08 UTC
    For the file names you've shown, a simple regex looking for 8 digits will do it:
    /\d{8}/
    Now, assuming you are not going to look for Apache logs dating from the twentieth century and that your program is likely to be obsolete in the 22nd century, you could narrow down the search:
    /\b20\d{6}\b/
    or narrow it down even further with something like this (untested):
    /\b20[12]\d[01]\d[0123]\d\b/
    (Of course, it is up to you to add capturing parentheses if you need.)
Re: Extracting datapart (YYYYMMDD) with filename regular expression
by tybalt89 (Monsignor) on Dec 01, 2016 at 15:47 UTC
    #!/usr/bin/perl -l # http://perlmonks.org/?node_id=1177054 use strict; use warnings; my $date; ($date) = /\b(2\d{7})\b/ and print $date while <DATA>; __DATA__ apachelog_LT100.7.7.7_21.SRV.apache.20161130-123456.258976.log APACHE_PP1.20161130-12:39:55-30822.Release.LT100.7.7.7.PP1.log APACHE_PS_PP1.20161130-15:29:37-5319.ebf_run.LT100.7.7.7.log