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

foo*_*.ar 3 perl replace newline sed multiline

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

void func_foo();
void func_bar();

//supercrazytag
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

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.

Joe*_*Fan 11

对于"perl -pe",你的问题是它是逐行处理的,所以它无法找到"\n \n".如果将-0777标志添加到Perl(以使其立即处理整个文件),它将起作用:

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

我还将(不适用于此用法)\ 1更改为$ 1,并在替换开头添加了额外的"\n"以提高可读性.

有关奇怪的"-0777"的解释,请参阅perlrun(命令开关)

  • 这真的非常容易阅读(除了 -0777,正如你所说,它看起来有点奇怪),但是 sed 和朋友们并没有接近这个简单的语法。 (2认同)