Perl - Regex para leer el archivo de registro

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.

preguntado el 09 de marzo de 12 a las 15:03

"_" is not "space", its underscore. " " is space. -

3 Respuestas

Qué tal si:

use strict;
use warnings;
use 5.010;

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

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

respondido 09 mar '12, 16:03

this is perfect,but keep in mind im scanning a log file. So I need to go over all the lines and use whatever is before the : as key, and everything after the : as value. - Nuevo estudiante

@NewLearner: I don't really understand what you mean. Do you want to keep all stuff in a hash? - Toto

Yesssss. That what I wanted. sorry I'm new to all this. - Nuevo estudiante

@NewLearner Be aware that if you use a hash, the keys will be overwritten. E.g. if you have foo: bar y foo: baz, only the later value will be in the resulting hash. - TLP

Or you could use a one liner like:

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

respondido 09 mar '12, 16:03

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


respondido 09 mar '12, 15:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.