[英]How to read from specific line to another line - Perl
I'm doing a Perl script and I have a log file where I need to extract data from. 我正在执行Perl脚本,并且有一个日志文件需要从中提取数据。 I want to know how to read from a specific line to another line(not end of file).
我想知道如何从特定行读取到另一行(不是文件末尾)。
I tried it this way by putting a last if
if it reaches the line that I want to stop at but it doesn't work. 我以这种方式尝试了此方法,如果到达了我要停止的行,则放
last if
但不起作用。 The line that I want to start reading from is <TEST_HEAD TH 1>
and stops at </TEST_HEAD TH 1>
. 我要开始读取的行是
<TEST_HEAD TH 1>
并停止在</TEST_HEAD TH 1>
。 I'm doing this because my regular expression captures data that I do not need, so I tried to read from a specific line to another line. 我这样做是因为我的正则表达式捕获了不需要的数据,因此我尝试从特定行读取到另一行。
This is what I've done so far: 到目前为止,这是我所做的:
while(<$log_fh>)
{
if($. =~ /\<TEST_HEAD TH 1\>/)
{
if ( /Computer Name:\s*(\S+)(-\d+)/i )
{
$details{tester_name} = $1 . $2;
$details{tester_type} = $1;
push @{$details{tester_arr}}, $1 . $2;
}
elsif ( /Operating System:\s*(.*\S)/i )
{
$details{op_sys} = $1;
}
elsif ( /IG-XL Version:\s*([^;]*)/i )
{
$details{igxl_vn} = $1;
}
elsif ( /^([\d]+)\.\d\s+(\S+)\s+([\d-]*)\s+([\d|\w]*)(?=\s)/ )
{
push @{$details{slot}}, $1;
push @{$details{board_name}}, $2;
push @{$details{part_no}}, $3;
push @{$details{serial_no}}, $4;
}
last if $. == /\<\/TEST_HEAD TH 1\>/;
}
}
Just a modified sample of the raw data file: 只是原始数据文件的修改示例:
<TEST_HEAD TH 1> #Start reading here
(Lines containing data to be captured)
</TEST_HEAD TH 1> #end reading here
Without going much into the nested matching logic you may want to change 在不深入探讨嵌套匹配逻辑的情况下,您可能需要更改
if($. =~ /\<TEST_HEAD TH 1\>/)
into 进入
if (/<TEST_HEAD TH 1>/ .. /<\/TEST_HEAD TH 1>/)
What you ask is actually XY problem and it would be better to process xml like document with xml parser. 您要问的实际上是XY问题,最好使用xml解析器处理xml(如文档)。 Parsing complex XML in Perl
在Perl中解析复杂的XML
Without knowing specifically how your data looks, I'd also offer another approach. 在不特别了解您的数据外观的情况下,我还会提供另一种方法。
Set $/
to a record separator, and then you grab a chunk of text in one go. 将
$/
设置$/
记录分隔符,然后您可以一次性捕获一大堆文本。 You can then apply a bunch of different regexes to it all at once. 然后,您可以一次将一堆不同的正则表达式应用到其中。
Eg: 例如:
local $/ = 'TEST_HEAD';
while (<$log_fh>) {
next unless m/^\s*TH/;
my ( $tester_name, $tester_id ) = (m/Computer Name:\s*(\S+)(-\d+)/i);
my ($op_sys) = (m/Operating System:\s*(.*\S)/i);
my ( $slot, $board, $part, $serial ) =
(m/^([\d]+)\.\d\s+(\S+)\s+([\d-]*)\s+([\d|\w]*)(?=\s)/m);
# etc.
# then validate and update your array:
$details{$tester_name} = $tester_name;
## etc.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.