有条件地删除fi中两个模式之间的线

2024-04-26 20:41:27 发布

您现在位置:Python中文网/ 问答频道 /正文

输入文件:

<Chunk of text>
PATTERN1
ABC
EFG
HIJ
PATTERN2
KLM
NOP
PATTERN3
<Chunk of text>

输出文件:

^{pr2}$

如何删除文件的模式1和模式3之间的行(包括模式2)


Tags: 文件oftext模式nopabcchunkpr2
2条回答

如果您当前处于两个模式(或行号)之间,那么这里的工作工具可能是range operator-tests。在

  • 测试是否介于PATTERN1和PATTERN3之间。在
  • 存储在缓冲区中
  • 当你点击“PATTERN3”,然后检查你是否看到了PATTERN2,然后打印或者丢弃你的缓冲区。在

例如:

#!/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>
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

相关问题 更多 >