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

时间:2014-09-02 10:10:12

标签: 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$myline\E/) {
                       ### 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 ####

我无法知道如何添加\替换部分,以及如何将我编辑的文件保存回文件(而不是数组

谢谢你 沙哈尔

3 个答案:

答案 0 :(得分:3)

使用splice更改@LINES的内容。

使用openprint@LINES写回您的文件。

如果其他人可能同时编辑此文件,则您需要flock

如果表现对您不重要,那么您可以查看Tie::File

对于更复杂的文件处理,您可能需要seektruncate

但在Perl常见问题解答 - How do I change, delete, or insert a line in a file, or append to the beginning of a file?

中已经很好地涵盖了这一点

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

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

答案 1 :(得分:1)

我建议采用另一种方法逐行处理文件,并在用户指定的$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 file\n";
  }
};
edit_file($edit, "file");

答案 2 :(得分:0)

您可以使用模块File :: Slurp来读取,写入,追加,编辑行,在文件中插入新行等等。

http://search.cpan.org/~uri/File-Slurp-9999.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$line\E$/$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$line\E$/$line\n$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$line\E$/ } $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