in reply to Need help in extracting timestamp from the line in a file

If your dates are very consistently formatted like that, then you can probably just create a regex to extract all the parts and reformat it. It's a decent intro regex problem.

If your dates are more complicated (e..g Third tuesday of the month) then Date::Manip is probably a good starting point. Sometimes Date::Manip doesn't have quite what you need a little pre-processing of your target data using a regex before you feed it to Date::Manip. It will probably also handle your dates as formatted, maybe with a little preprocessing.

  • Comment on Re: Need help in extracting timestamp from the line in a file

Replies are listed 'Best First'.
Re^2: Need help in extracting timestamp from the line in a file
by jayu_rao (Sexton) on Mar 09, 2015 at 16:24 UTC

    Thanks for the suggestion. This is the Regex that I've come up with:

    if($_=~/Launching the JVM/){ /\-+ [A-Za-z]{3} (.*?) (.*?) (.*?)\:(.*?)\:(.*?) (\d+)::(\d+)::Launchi +ng the JVM with following options/; if ( $1 eq "Jan") { $month= "01";} if ( $1 eq "Feb") { $month= "02";} ... if ( $1 eq "Dec") { $month= "12";} if ( $2 eq " 1") { $start_date= "01";} if ( $2 eq " 2") { $start_date= "02";} ... if ( $2 eq " 9") { $start_date= "09";} if ( $3 eq " 1") { $start_hour= "01";} if ( $3 eq " 2") { $start_hour= "02";} ... if ( $3 eq " 9") { $start_hour= "09";} if ( $4 eq "1") { $start_min= "01";} if ( $4 eq "2") { $start_min= "02";} ... if ( $4 eq "9") { $start_min= "09";} if ( $5 eq "1") { $start_sec= "01";} if ( $5 eq "2") { $start_sec= "02";} ... if ( $5 eq "9") { $start_sec= "09";} print "App Start time is: $6-$month-$start_date $start_hour:$start_min +:$start_sec\n";

    However, it is failing to convert if the date / hour / min / sec is a single digit / character 0-9 and prints it something like:

    $perl get_ts.pl

    --------------------------------------

    App Start time is: 2015-04- 8 1:51:20

    --------------------------------------

    Not sure what I am doing wrong. I tried replacing .*? to \d+ but still not getting the desired results.

    Can you please suggest?

      You should check whether the match succeeds at all.
      if (/\-+ [A-Za-z]{3} (.*?) (.*?) (.*?)\:(.*?)\:(.*?) (\d+)::(\d+)::Lau +nching the JVM with following options/) { ...

      Also, use hashes and sprintf to format the numbers and convert month names:

      # Declaration my $m = 1; my %MONTH = map { $_ => $m++ } qw( Jan Feb Mar Apr May ... ); # Later in the code: $month = sprintf '%02d', $MONTH{$1};
      لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ