Latest LQ Deal: Linux Power User Bundle
Go Back > Forums > Non-*NIX Forums > Programming
User Name
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.


  Search this Thread
Old 01-22-2009, 10:15 AM   #1
Registered: Oct 2004
Posts: 98

Rep: Reputation: 15
Question 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.

$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?
Old 01-22-2009, 10:23 AM   #2
Registered: May 2007
Distribution: Debian
Posts: 754

Rep: Reputation: 59
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:
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.
my $stime = $1 if $1;

Last edited by Telemachos; 01-22-2009 at 10:25 AM.
Old 01-22-2009, 10:56 AM   #3
Registered: Oct 2004
Posts: 98

Original Poster
Rep: Reputation: 15
Thanks! This works.


date, parse, perl, regex, time

Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
how to convert windows date and time to unix date and time jitupatil_2007 General 8 03-31-2008 05:58 AM
Put a date/time from the command line Jzarecta Linux - Software 1 10-03-2007 12:48 PM
BASH RegEx file name parsing Hewson Linux - General 7 04-27-2007 05:37 PM
Start Date + Time Duration = End Date/Time calculator? ToBe Linux - General 3 09-26-2005 10:17 AM > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 03:17 AM.

Main Menu
Write for LQ is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration