如何使用perl添加和替换行数组中的行



我想通过添加一些行并替换其他行来编辑文件。我正在尝试使用一个逐行包含我的文件的数组,即

    my $output_file_string = `cat $result_dir/$file`;
    my @LINES = split(/n/, $output_file_string);

我有一个行的哈希表,我想在文件中找到,并替换它们或在它们后面添加额外的行。我写了以下代码来识别这些行:

        foreach my $myline (keys %{ $hFiles_added{$file} }) { 
            foreach my $line ( @LINES) {
                  if ($line =~ /Q$mylineE/) {
                       ### here should be a code for adding a new line after the current line ###
                  }
             }
        }
        #### here should be a code to return the array to the output file ####

我不知道如何添加/替换零件,以及如何将编辑后的文件保存回文件中(而不是数组

谢谢Shahar

使用splice更改@LINES的内容。

使用"打开并打印"将@LINES写回文件。

如果其他人可能同时编辑这个文件,那么你需要羊群。

如果性能对您来说不是那么重要,那么您可以查看Tie::File。

对于更复杂的文件处理,您可能需要查找和截断。

但这一切都在Perl常见问题解答中得到了很好的介绍——我如何在文件中更改、删除或插入一行,或者附加到文件的开头?

顺便说一下,你的前两行代码可以替换为一行:

my @LINES = `cat $result_dir/$file`;

我建议采用另一种方法,逐行处理文件,并在用户指定的$edit函数中修改行。

use strict;
use warnings;
sub edit_file {
  my $func = shift;
  # perl magic for inline edit
  local @ARGV = @_;
  local $^I = "";
  local $_;
  while (<>) {
    $func->(eof(ARGV));
  }
}

my $edit = sub {
  my ($eof) = @_;
  # print to editing file
  print "[change] $_";
  if ($eof) {
    print "adding one or more line to the end of filen";
  }
};
edit_file($edit, "file");

您可以使用模块File::Slurp来读取、写入、追加、编辑行、在文件中插入新行以及其他许多操作。

http://search.cpan.org/~uri/File-Slurp-999999.19/lib/File/Slurp.pm

use strict;
use warnings;
use File::Slurp 'write_file', ':edit';
my $file = './test.txt';
#The lines you want to change with their corresponding values in the hash:
my %to_edit_line = ( edit1 => "new edit 1", edit2 => "new edit 2" );
foreach my $line ( keys %to_edit_line ) {
    edit_file_lines { s/^Q$lineE$/$to_edit_line{$line}/ } $file;
}
#The lines after you want to add a new line:
my %to_add_line = ( add1 => 'new1', add2 => 'new2' );
foreach my $line ( keys %to_add_line ) {
    edit_file_lines { s/^Q$lineE$/$linen$to_add_line{$line}/ } $file;
}
#The lines you want to delete:
my %to_delete_line = ( del1 => 1, del2 => 1 );
foreach my $line ( keys %to_delete_line ) {
    edit_file_lines { $_ = '' if /^Q$lineE$/ } $file;
}
#You can also use this module to append to a file:
write_file $file, {append => 1}, "the line you want to append";
The original file test.txt had the following content:
zzz
add1
zzz
del1
zzz
edit1
zzz
add2
zzz
del2
zzz
edit2
zzz
After running the program, the same file has the following content:
zzz
add1
new1
zzz
zzz
new edit 1
zzz
add2
new2
zzz
zzz
new edit 2
zzz
the line you want to append

最新更新