NewLearner
NewLearner

Reputation: 223

Perl - Regex to read log file

I read and did not find the answer. I want to read a log file and print out everything after the ":" but some of the log have space before some dont. I want to match only the one with not space at the beginning.

_thisnot: this one has space
thisyes: this one has not space at the beginning.

I want to do that for every line in the file.

Upvotes: 3

Views: 2084

Answers (3)

Toto
Toto

Reputation: 91518

How about:

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

my %result;
while(<DATA>) {
    chomp;
    next if /^\s/;
    if (/^([^:]*):\s*(.*)$/) {
        $result{$1} = $2;
    }
}

__DATA__
 thisnot: this one has space
thisyes: this one has not space at the beginning.

Upvotes: 1

Qtax
Qtax

Reputation: 33928

Or you could use a one liner like:

perl -ne 's/^\S.*?:\s*// && print' file.log

Upvotes: 1

DVK
DVK

Reputation: 129529

# Assuming you opened log filehandle for reading...
foreach my $line (<$filehandle>) {
    # You can chomp($line) if you don't want newlines at the end
    next if $line =~ /^ /; # Skip stuff that starts with a space
              # Use  /^\s/ to skip ALL whitespace (tabs etc)
    my ($after_first_colon) = ($line =~ /^[^:]*:(.+)/);
    print $after_first_colon if $after_first_colon; # False if no colon. 

}

Upvotes: 0

Related Questions