Perl - Regex to read log file

I read and couldn't find an answer. I want to read the log file and print everything after the ":", but some of the logs have a place before some. I want to combine only the one who has no place at the beginning.

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

      

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

+3


source to share


3 answers


What 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.

      

+1


source


Or you can use one liner like:



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

      

+1


source


# 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. 

}

      

0


source







All Articles