Match and replace multiple lines of a new line using SED or PERL single-line dialing

I have a C input file (myfile.c) that looks like this:

void func_foo();
void func_bar();

//supercrazytag

I want to use the shell command to insert new function prototypes, so the output will look like this:

void func_foo();
void func_bar();
void func_new();

//supercrazytag

So far I have not used SED or PERL. What did not work out:

sed 's|\n\n//supercrazytag|void func_new();\n\n//supercrazytag|g' < myfile.c
sed 's|(\n\n//supercrazytag)|void func_new();\1|g' < myfile.c

Using the same templates with perl -pe "....." does not work either.

What am I missing? I tried many different approaches, including this and this and that .

+3
source share
4 answers

"perl -pe" , , "\n\n". -0777 Perl ( ), :

perl -0777 -pe "s|(\n\n//supercrazytag)|\nvoid func_new();$1|g" myfile.c

( ) \1 $1 "\n" .

. perlrun (Command Switches) "-0777"

+11

:

sed '/^$/N;s|\n//supercrazytag|void func_new();\n\n//supercrazytag|' myfile.c

:
:

sed '/^$/N;s|\(\n//supercrazytag\)|void func_new();\n\1|' myfile.c
+2

, , .

In the pseudo-code:
1. start reading and writing lines from the file
2. When we find the end of the prototype section, insert the new text

use strict;
use warnings;

my $new_prototype = 'void func_new();';
my $seen_proto;

while (<>)
{
    if (/^void \w+\(\);$/ .. /^$/)
    {
        # in the middle of the prototype section
        $seen_proto = 1;
    }
    else
    {
        # this code is run when either before or after the prototype section

        # if we have seen prototypes, we're just after that section - print
        # out the new prototype and then reset our flag so we don't do it twice
        print "$new_prototype\n" and $seen_proto-- if $seen_proto;
    }

    # print out the original line
    print;
}

Put this code in process.pl and run through: perl process.pl < mycode.cpp > mycode_new.cpp

0
source
awk  '/supercrazy/{$0="void func_new()\n\n"$0}1'  file
0
source

Source: https://habr.com/ru/post/1757190/


All Articles