输入文件:
<Chunk of text>
PATTERN1
ABC
EFG
HIJ
PATTERN2
KLM
NOP
PATTERN3
<Chunk of text>
输出文件:
<Chunk of text>
<Chunk of text>
仅当文件之间存在PATTERN2时,如何删除文件的PATTERN 1和PATTERN 3之间的线条(包括)
答案 0 :(得分:0)
此处作业的工具可能是范围操作员 - 如果您当前处于两种模式(或行号)之间,则进行测试。
E.g:
#!/usr/bin/env perl
use strict;
use warnings;
my @buffer;
my $found = 0;
while ( <DATA>) {
#check we are between patterns
if ( m/PATTERN1/ .. m/PATTERN3/ ) {
#test if pattern 2 is in this chunk.
if ( m/PATTERN2/ ) { $found++; }
#stash this line
push @buffer, $_;
}
else {
#outside pattern1..pattern3
#do we have a pending buffer? (e.g. just finished)
if ( @buffer ) {
#print if we didn't see a pattern 2
if ( not $found ) { print @buffer }
#reset buffer and count of pattern 2.
$found = 0;
@buffer = ();
}
#print current line.
print;
}
}
__DATA__
<Chunk of text>
PATTERN1
ABC
EFG
HIJ
PATTERN2
KLM
NOP
PATTERN3
<Chunk of text>
答案 1 :(得分:0)
import sys,re
flaG,deletE,storE = False,False,""
for linE in open(sys.argv[1]):
if re.search('pattern1',linE):
flaG = True
print storE
storE = linE
continue
if flaG :
storE += linE
if re.search('pattern2',linE): deletE = True
if re.search('pattern3',linE) :
if not deletE : print storE
storE = ''
flaG = False
deletE = False
else : print linE,
print storE