gpt4 book ai didi

regex - 除非遇到两个连续的新行,否则如何为每两行插入一个新行?

转载 作者:行者123 更新时间:2023-12-01 07:52:27 24 4
gpt4 key购买 nike

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

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

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'

关于regex - 除非遇到两个连续的新行,否则如何为每两行插入一个新行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43224527/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com