文件1
--- abcd10 ---
--- abcd31 ---
--- abcd32 ---
MY Addr info name policy
---------------------------------------------------------
00:0a:91:00:65:93 HQLT DKAHN Default
--- abcd33 ---
No info found
--- abcd34 ---
No info found
--- abcd35 ---
MY Addr info name policy
---------------------------------------------------------
00-0a-91-00:15:03 HQ-LT-DKAHN Default
00-0a-91-10:15:03 HQ-LT-DKAHN Default
在上面的文件中我只想提取特定的格式。
--- abcd32 ---
MY Addr info name policy
---------------------------------------------------------
00:0a:91:00:65:93 HQLT DKAHN Default
和
--- abcd35 ---
MY Addr info name policy
---------------------------------------------------------
00-0a-91-00:15:03 HQ-LT-DKAHN Default
00-0a-91-10:15:03 HQ-LT-DKAHN Default
代码:
#!/usr/bin/perl
use warnings;
use strict;
my $file;
my $start_marker_mqstats = qr{^\-+\s*\w+\s*\-+.* $}x;
my $end_marker_mqstats = qr{^\s* $}x;
open($file,"<", "file") || die $!;
while(<$file>) {
if ($_ =~/^\-\-\-\s\w+\s\-\-\-/){
if ($_ =~/^MY\sAddr.*/){
next unless my $range = /$start_marker_mqstats/ .. /$end_marker_mqstats/;
my $line = $_;
print $line if $range !~ /^1$|E/;
}
}
}
答案 0 :(得分:1)
您可以使用段落模式(设置$/ = ""
)和&#34; grep&#34;对于以MY
开头的行,使用/m
正则表达式修饰符将换行符匹配为^
。
perl -00 -nlwe"print if /^MY /m" input.txt
-00
将输入记录分隔符$/
设置为""
。
或作为程序文件:
$/ = "";
while (<>) {
print if /^MY /m;
}
在这两种情况下,输出为:
--- abcd32 ---
MY Addr info name policy
---------------------------------------------------------
00:0a:91:00:65:93 HQLT DKAHN Default
MY Addr info name policy
---------------------------------------------------------
00-0a-91-00:15:03 HQ-LT-DKAHN Default
00-0a-91-10:15:03 HQ-LT-DKAHN Default
第二种情况下缺少的标题是因为样本输入中有一个空行。我猜这是你的复制/粘贴错误,而不是你输入的错误。