Perl - Insert lines after a match is found in a file

前端 未结 5 1681
南笙
南笙 2021-01-24 09:34

I have a file with the following syntax in some_1.xyz

module some_1 {
INPUT PINS
OUTPUT PINS
}

and I want to insert APPLY DELAYS xx and APPLY L

相关标签:
5条回答
  • 2021-01-24 10:09
    $text='bla bla mytext bla bla';
    $find='.*mytext.*';
    $repl='replacement';
    
    $text=~ s/($find)/$1$repl/g;
    

    $1 is basically your match and you can use it when you make the replacement, either before or after your $repl string. )))

    EASY

    0 讨论(0)
  • 2021-01-24 10:10

    And what's wrong with the easy solution?:

    $data=`cat /the/input/file`;
    $data=~s/some_1 {\n/some_1 {\nAPPLY DELAYS xx\nAPPLY LOADS ld\n/gm;
    print $data;
    
    0 讨论(0)
  • 2021-01-24 10:11

    Something much simpler, in just one line using SED (in case this question is for UNIX only and when the match is a fixed value, not regular expression):

    sed -i -e "s/<match pattern>/<match pattern>\n<new line here>/g" file.txt
    

    (The options have been swapped compared to the initial response, because the first comment.)

    Notice the \n is to add a new line. Regards

    0 讨论(0)
  • 2021-01-24 10:16

    one-liner

    perl -pi -e '/module some_1/ and $_.="APPLY DELAY xx \nAPPLY LOADS  ld\n"' files*.txt
    
    0 讨论(0)
  • 2021-01-24 10:22

    I have no idea why your code isn't working, but I have trouble following your use of Perl inside backticks inside Perl. This is untested, but should work. I suggest you also "use strict;" and "use warnings;".

    my @files = ("some_1.xyz", "some_2.xyz", ... );
    for my $file in ( @files )
    {
        my $outfile = $file + ".tmp";
        open( my $ins, "<", $file ) or die("can't open " . $file . " for reading: " . $!);
        open( my $outs, ">", $outfile ) 
            or die("can't open " . $outfile . " for writing: " . $!);
        while ( my $line = <$ins> )
        {
            print { $outs } $line;
            if ( $line =~ m/^module\s+/ )
            {
                 print { $outs } "\tAPPLY DELAY xx\n\tAPPLY LOADS ld\n";
            }
        }
        rename( $outfile, $file );
    }
    
    0 讨论(0)
提交回复
热议问题