LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Regex: How do I put this on one line? (Time-date parsing) (https://www.linuxquestions.org/questions/programming-9/regex-how-do-i-put-this-on-one-line-time-date-parsing-699142/)

RavenLX 01-22-2009 10:15 AM

Regex: How do I put this on one line? (Time-date parsing)
 
I'm not great at regex so I'll try to explain what I have.

Code:


$line = "Log Created: [12/Dec/2008:06:35:15 -0800] by MyScript on 'ubuntu 8.04 LTS' - - Details: 1/2/3";

$stime = $& if $line =~ /\[.+\]/;
$stime =~ s/^\[//;
$stime =~ s/\]$//;
print "$stime\n";

Would like to put this into $stime in one line instead of 3 so that $stime would have "12/Dec/2008:06:35:15 -0800".

Someone know how to do this?

Telemachos 01-22-2009 10:23 AM

If I understand you, and the lines look like your sample does, it's not too bad. Essentially you want to capture everything in between [ and ] and leave the time stuff in the order it's found. This works using Perl:
Code:

#!/usr/bin/perl
use strict;
use warnings;

my $line = "Log Created: [12/Dec/2008:06:35:15 -0800] by MyScript on 'ubuntu 8.04
LTS' - - Details: 1/2/3";

$line =~ m/\[(.+)\]/;
my $stime = $1;

print "$stime\n";

If you have multiple instances of [stuff] on any given line or stretching across lines, things get uglier. The parentheses () put the captured items into numbered scalars ($1, $2, etc.) for use later. Depending on how reliable your output is, it probably pays to check for the existence of $1 before you try to use it.
Code:

my $stime = $1 if $1;

RavenLX 01-22-2009 10:56 AM

Thanks! This works. :)


All times are GMT -5. The time now is 03:40 PM.