Perl 读取文件并抓取特定行
我有一个文本文件,我想抓取以模式开头并以特定模式结尾的特定行。 示例:
Text
Text
Startpattern
print this line
Print this line
print this line
Endpattern
Text
Text
Text
还应打印起始图案和结束图案。我的第一次尝试并不成功:
my $LOGFILE = "/var/log/logfile";
my @array;
# open the file (or die trying)
open(LOGFILE) or die("Could not open log file.");
foreach $line () {
if($line =~ m/Sstartpattern/i){
print $line;
foreach $line2 () {
if(!$line =~ m/Endpattern/i){
print $line2;
}
}
}
}
close(LOGFILE);
提前感谢您的帮助。
I have a text file and I want to grab specific lines starting with a pattern and ending with a specific pattern.
Example:
Text
Text
Startpattern
print this line
Print this line
print this line
Endpattern
Text
Text
Text
Also the start pattern and the end pattern should be printed. My first try was not really successful:
my $LOGFILE = "/var/log/logfile";
my @array;
# open the file (or die trying)
open(LOGFILE) or die("Could not open log file.");
foreach $line () {
if($line =~ m/Sstartpattern/i){
print $line;
foreach $line2 () {
if(!$line =~ m/Endpattern/i){
print $line2;
}
}
}
}
close(LOGFILE);
Thanks in advance for your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用标量范围运算符:
You can use the scalar range operator:
怎么样:
如果您还希望打印开始和结束模式,请也在该 if 块中添加 Push 语句。
How about this:
If you want the start and end patterns to also be printed, add the push statements in that if block as well.
像这样的东西吗?
Something like this?