2012-03-09 58 views
3

我看了,没有找到答案。 我想读取一个日志文件并打印出“:”后面的所有内容,但有些日志文件在某些​​日志文件之前有空格。我只想匹配一开始就没有空格的那个。Perl - 正则表达式读取日志文件

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

我想为文件中的每一行这样做。

+0

' “_”'不是 “空间”,其下划线。 '“”'是空格。 – TLP 2012-03-09 17:04:07

回答

1

如何:

#!/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. 
+0

这是完美的,但请记住即时扫描日志文件。因此,我需要仔细检查所有行,并使用:as之前的任何内容,以及:as之后的所有内容。 – NewLearner 2012-03-09 16:03:38

+0

@新学员:我不太明白你的意思。你想保留所有的东西在一个哈希? – Toto 2012-03-09 16:22:04

+0

Yesssss。那是我想要的。抱歉,我对这一切都很陌生。 – NewLearner 2012-03-09 16:39:12

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

} 
1

或者你可以使用一个衬垫,如:

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