使用 Perl 提取特定行 [英] Extracting specific lines with Perl
问题描述
我正在编写一个 perl 程序来提取我匹配的两个模式之间的行.例如下面的文本文件有 6 行.我正在匹配负载平衡器并结束.我想获得介于两者之间的 4 行.
I am writing a perl program to extract lines that are in between the two patterns i am matching. for example the below text file has 6 lines. I am matching load balancer and end. I want to get the 4 lines that are in between.
**load balancer**
new
old
good
bad
**end**
我的问题是如何将负载均衡器之间的行提取到数组中.任何帮助是极大的赞赏.
My question is how do you extract lines in between load balancer and end into an array. Any help is greatly appreciated.
推荐答案
您可以使用 触发器运算符.
另外,你也可以使用触发器的返回值来过滤掉边界线.返回值是一个序列号(从 1 开始),最后一个数字附加了字符串 E0
.
Additionally, you can also use the return value of the flipflop to filter out the boundary lines. The return value is a sequence number (starting with 1) and the last number has the string E0
appended to it.
# Define the marker regexes separately, cuz they're ugly and it's easier
# to read them outside the logic of the loop.
my $start_marker = qr{^ \s* \*\*load \s balancer\*\* \s* $}x;
my $end_marker = qr{^ \s* \*\*end\*\* \s* $}x;
while( <DATA> ) {
# False until the first regex is true.
# Then it's true until the second regex is true.
next unless my $range = /$start_marker/ .. /$end_marker/;
# Flip-flop likes to work with $_, but it's bad form to
# continue to use $_
my $line = $_;
print $line if $range !~ /^1$|E/;
}
__END__
foo
bar
**load balancer**
new
old
good
bad
**end**
baz
biff
输出:
new
old
good
bad
这篇关于使用 Perl 提取特定行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!