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)
记忆消瘦2024-11-01 07:27:49
怎么样:
#!perl -w
use strict;
my $spool = 0;
my @matchingLines;
while (<DATA>) {
if (/StartPattern/i) {
$spool = 1;
next;
}
elsif (/Endpattern/i) {
$spool = 0;
print map { "$_ \n" } @matchingLines;
@matchingLines = ();
}
if ($spool) {
push (@matchingLines, $_);
}
}
__DATA__
Text
Text
Startpattern
print this line
Print this line
print this line
Endpattern
Text
Text
Text
Startpattern
print this other line
Endpattern
如果您还希望打印开始和结束模式,请也在该 if 块中添加 Push 语句。
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
您可以使用标量范围运算符:
You can use the scalar range operator: