[英]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. 我想对文件中的每一行都这样做。
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.
或者您可以使用如下的单线程:
perl -ne 's/^\S.*?:\s*// && print' file.log
# 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.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.