perl脚本从文件中删除行

时间:2015-10-15 15:33:16

标签: perl

我有一个文件,我想阅读它,并找到每个'字'删除接下来的2行,包括带有'word'的行。  这个文件的结构是这样的:

df1

这就是我现在所拥有的:

1
2
3
word
321
3213
412
word
132
1231

感谢

2 个答案:

答案 0 :(得分:4)

我做这样的事情:

#!/usr/bin/env perl
use strict;
use warnings;

#iterate one line at a time. 
while ( <DATA> ) {
    #if we hit the delimiter, read and discard two more line. 
    if ( m/word/ ) { <DATA>; <DATA> ; }  
    #otherwise print it. 
    else { print; };
}

__DATA__
1
2
3
word
321
3213
412
word
132
1231

给出了:

1
2
3
412

答案 1 :(得分:2)

优秀的Tie::File模块似乎经常被遗忘。这是理想的事情

use strict;
use warnings;

use File::Copy qw/ copy /;
use Tie::File;

my $local_dir = '.';

copy "$local_dir/x.txt", 'y.txt';
tie my @file, 'Tie::File', 'y.txt';

for ( my $i = 0; $i < @file; ) {
  if ( $file[$i] eq 'word' ) {
    splice @file, $i, 3;
  }
  else {
    ++$i;
  }
}

输出

1
2
3
412
相关问题