使用SED或PERL单线匹配和替换多个换行符 [英] match and replace multiple newlines with a SED or PERL one-liner

查看:171
本文介绍了使用SED或PERL单线匹配和替换多个换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的输入C文件(myfile.c):

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

void func_foo();
void func_bar();

//supercrazytag

我想使用shell命令插入新的函数原型,以使输出变为:

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

到目前为止,我使用SED或PERL一直没有成功. 什么不起作用:

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

使用与perl -pe"....."相同的模式也不起作用.

Using the same patterns with perl -pe "....." didn't work either.

我想念什么?我尝试了许多不同的方法,包括 this

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

推荐答案

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

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

我还将(不建议使用的)\ 1更改为$ 1,并在替换开始时添加了一个额外的"\ n"以提高可读性.

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

有关奇怪外观的说明,请参见 perlrun(命令开关) "-0777"

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

这篇关于使用SED或PERL单线匹配和替换多个换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆