【问题标题】:Perl - Searching a file for specific text and deleting a range of lines [duplicate]Perl - 在文件中搜索特定文本并删除一系列行[重复]
【发布时间】:2011-02-22 03:26:55
【问题描述】:

可能重复:
How do I change, delete, or insert a line in a file, or append to the beginning of a file in Perl?

我将如何使用 perl 打开文件,查找某人输入的项目,如果找到,它将从该行删除到下面的 14 行。

【问题讨论】:

  • 我尝试过使用 sed 命令,但我无法让它传入变量,它实际上并没有保存到文件中,它只输出结果。我是 perl 的初学者

标签: perl


【解决方案1】:

这样的事情会起作用:

#!/usr/bin/env perl
use Modern::Perl;
use IO::File;

say "Enter a pattern please: ";
chomp (my $input = <>);
my $pattern;
# check that the pattern is good
eval {
    $pattern = qr ($input);
}; die $@ if $@;

my $fh = IO::File->new("test.txt", "+<") or die "$!\n";
my @lines = $fh->getlines;
$fh->seek(0,0);
for (my $pos = 0; $pos < $#lines; ++$pos) {
    if ($lines[$pos] =~ $pattern) {
        $pos += 14;
    } else {
        print {$fh} $lines[$pos];
    }
}
$fh->close;
$|++

【讨论】:

  • 如果文件很大,这会占用大量内存。
  • 是的,我想过这个,但由于他没有说文件有多大,我想它可能会很小。
【解决方案2】:
#!/usr/bin/env perl
use strict;
use warnings;
use autodie;

my $filename = 'filename.txt';
my $tmp = 'filename.txt.tmp';

print "Enter a pattern please: ";
chomp (my $input = <>);
my $pattern = qr($input)x;

open my $i_fh, '+<', $filename;
open my $o_fh, '>',  $tmp;

while(<$i_fh>){
  # move print here if you want to print the matching line
  if( /$pattern/ ){
    <$i_fh> for 1..14;
    next;
  }
  print {$o_fh} $_ ;
}

close $o_fh;
close $i_fh;

use File::Copy

move $tmp, $filename;

【讨论】:

    猜你喜欢
    • 2023-02-20
    • 2013-09-29
    • 1970-01-01
    • 1970-01-01
    • 2016-05-03
    • 1970-01-01
    • 1970-01-01
    • 2018-07-27
    • 2018-05-23
    相关资源
    最近更新 更多