2014-09-02 75 views
4

我想通过添加某行并替换其他行来编辑文件。 我试图与包含线我的文件行的数组工作,即如何使用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 #### 

我想不出如何做加法\更换部分,以及如何保存我的编辑过的文件早在一个文件中(而不是阵列

谢谢 沙哈尔

+0

不知道你的意思....我需要在最后用一些新的线路和一些raplaced线原始文件 – user3350919 2014-09-02 10:21:28

+0

参见[perlfaq5(HTTP://的perldoc。 perl.org/perlfaq5.html#How-do-I-change,-delete,-or-insert-a-line-in-a-file,-or-append-to-the-beginning-of-a-file ?) – RobEarl 2014-09-02 10:33:27

回答

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

我建议另一种方法,即文件被逐行处理,并且在用户指定的$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"); 
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 
相关问题