微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

正则表达式 – 除了遇到两个连续的新行之外,如何为每两行插入一个新行?

我试图为每两行文本插入一个新行,除非我想在遇到新段落(连续两行)时重新启动此模式. (我想要的输出不应该有三个连续的新行.)

例如,这是我的输入文本:

This is my first
line to appear in
the text.

I need the second
line to appear in
the way that follows
the pattern specified.

I am not sure if
the third line will
appear as I want it
to appear because sometimes
the new line happens where
there are two consecutive 
new lines.

这是我想要的输出

This is my first
line to appear in

the text.

I need the second
line to appear in

the way that follows
the pattern specified.

I am not sure if
the third line will

appear as I want it
to appear because sometimes

the new line happens where
there are two consecutive

new lines.

我试过用awk:

awk -v n=2 '1; NR % n == 0 {print ""}'

但是此命令在新段落后不会重新启动模式.相反,我会从上面的示例文本中获得以下输出

This is my first
line to appear in

the text.


I need the second

line to appear in
the way that follows

the pattern specified.


I am not sure if
the third line will

appear as I want it
to appear because sometimes

the new line happens where
there are two consecutive

new lines.

由于这个不需要的输出显示,没有重新启动模式,我将得到三个连续新行的实例.

解决方法

perl中的段落模式可以帮助:

perl -00 -ple 's/.*\n.*\n/$&\n/g'

产量

This is my first
line to appear in

the text.

I need the second
line to appear in

the way that follows
the pattern specified.

I am not sure if
the third line will

appear as I want it
to appear because sometimes

the new line happens where
there are two consecutive 

new lines.

基于@Borodin评论

perl -00 -ple 's/(?:.*\n){2}\K/\n/g'

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐