How to add and replace lines in a line array with perl

后端 未结 3 644
北恋
北恋 2021-01-19 08:11

I want to edit a file by adding some line and replacing some others. I\'m trying to work with an array that contains my file line by line, i.e

    my $outpu         


        
3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-19 08:28

    You can use the module File::Slurp to read, write, append, edit the lines, insert new lines in the file and many other things.

    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
    

提交回复
热议问题