Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

grep question

by darrengan (Sexton)
on Nov 17, 2005 at 05:26 UTC ( #509293=perlquestion: print w/replies, xml ) Need Help??

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?

Cheers

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;

    Regards,
    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
    -kulls.
Re: grep question
by l.frankline (Hermit) on Nov 17, 2005 at 06:01 UTC

    Hi,

    Try this....

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

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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://509293]
Approved by jbrugger
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (5)
As of 2022-12-01 07:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?