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

Hi Monks,
Understand that from the file name file1_system_051117123050.txt, when i do a
grep /\d{8}\.txt$/

i will get 17123050. How do i only capture 1712?


Replies are listed 'Best First'.
Re: grep question
by monarch (Priest) on Nov 17, 2005 at 05:31 UTC
    If you had an array of file names, and did the following:
    my @grepped = grep /\d{8}\.txt$/ @filenames;
    ..then your array @grepped would contain the entry 'file1_system_051117123050.txt' if this filename was in the @filenames array.

    However, if you want to capture text from a string, then you want a regular expression match:

    if ( $filename =~ m/(\d{4})\d{4}.txt$/ ) { print( $1 . "\n" ); }
    ..if $filename contained 'file1_system_051117123050.txt' then you would have '1712' printed out as that was the four digits captured within parenthesis (curly brackets) in the regular expression match.
Re: grep question
by murugu (Curate) on Nov 17, 2005 at 05:54 UTC
    Hi darrengan,

    If you have a single filename then,

    my ($match)=$file=~/(\d{4})\d{4}\.txt/;

    If you have multiple filenames and you want to construct array of the results then,

    my @a = map {/(\d{4})\d{4}\.txt/} @filenamearray;

    Murugesan Kandasamy
    use perl for(;;);

Re: grep question
by Roger (Parson) on Nov 17, 2005 at 05:42 UTC
    I'd say something like this would work...
    my @capture = map { /(\d{4})\d{4}.txt/ } grep { ... } ...;

Re: grep question
by kulls (Hermit) on Nov 17, 2005 at 06:09 UTC
    I guess you are concatenating timestamp with your file name.if so then, you can create a ( Time::piece ) object using  strptime() function in this module.So that you can get the data from the object directly.Otherwise please tell me, how you generate this numbers, let we try that side also.
    more info for Time::piece
Re: grep question
by l.frankline (Hermit) on Nov 17, 2005 at 06:01 UTC


    Try this....

    $_= 'file1_system_051117123050.txt';
    ($_) = grep s/.*(\d{4})\d{4}\.txt/$1/, $_;
    print $_;

    Don't put off till tomorrow, what you can do today.