2014-09-02 58 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 
相關問題