Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

match and replace multiple newlines with a SED or PERL one-liner

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

void func_foo();
void func_bar();

//supercrazytag

I want to use a shell command to insert new function prototypes, such that the output becomes:

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

//supercrazytag

So far I've been unsuccessful using SED or PERL. What didn't work:

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 patterns with perl -pe "....." didn't work either.

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

like image 373
foob.ar Avatar asked Dec 07 '22 02:12

foob.ar


1 Answers

For "perl -pe", your problem is that it is processing line by line, so there is no way it will find "\n\n". If you add the -0777 flag to Perl (to make it process the whole file at once) it will work:

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

I also changed the (deprecated for this usage) \1 to $1 and added an extra "\n" to beginning of the replacement for readability.

See perlrun (Command Switches) for an explanation of the odd-looking "-0777"

like image 87
JoelFan Avatar answered Mar 06 '23 05:03

JoelFan