如何在Perl中提取两个行定界符之间的行? [英] How do I extract lines between two line delimiters in Perl?
问题描述
我有一个ASCII日志文件,其中包含一些我想提取的内容.我从来没有花时间来正确学习Perl,但是我认为这是完成此任务的好工具.
I have an ASCII log file with some content I would like to extract. I've never taken time to learn Perl properly, but I figure this is a good tool for this task.
文件的结构如下:
...
... some garbage
...
... garbage START
what i want is
on different
lines
END
...
... more garbage ...
next one START
more stuff I want, again
spread
through
multiple lines
END
...
more garbage
因此,我正在寻找一种方法来提取每个START
和END
分隔符字符串之间的行.
我该怎么办?
So, I'm looking for a way to extract the lines between each START
and END
delimiter strings.
How can I do this?
到目前为止,我仅找到了一些有关如何使用START
字符串打印行的示例,或与我正在寻找的内容有些相关的其他文档项目.
So far, I've only found some examples on how to print a line with the START
string, or other documentation items that are somewhat related with what I'm looking for.
推荐答案
您想要触发器运算符(通常称为范围运算符)..
You want the flip-flop operator (better known as the range operator) ..
#!/usr/bin/env perl
use strict;
use warnings;
while (<>) {
if (/START/../END/) {
next if /START/ || /END/;
print;
}
}
使用您实际想要执行的操作来替换对print
的调用(例如,将行压入数组,对其进行编辑,对其进行格式化等).我正在next
-经过实际上具有START
或END
的行,但是您可能不希望这种行为.请参阅本文,以获取有关此运算符和其他运算符的讨论.有用的Perl特殊变量.
Replace the call to print
with whatever you actually want to do (e.g., push the line into an array, edit it, format it, whatever). I'm next
-ing past the lines that actually have START
or END
, but you may not want that behavior. See this article for a discussion of this operator and other useful Perl special variables.
这篇关于如何在Perl中提取两个行定界符之间的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!