将空行及其下面的一行替换为使用 sed

将空行及其下面的一行替换为使用 sed

我有这样的东西;

One blank line below

> This is a text
> This is another line of text

One blank line above

试图得到这样的东西;

One blank line below

<blockquote>
> This is a text
> This is another line of text
</blockquote>

One blank line above

尝试过这个;

sed 's/^\n\(>\)/\r<blockquote>\r\1/g' test.txt

and

sed 's/^\(>.*\)\n$/\1\r<\/blockquote>\r/g' test.txt

当我在 vim (8.1) 中时,这些正则表达式对我来说工作得很好,但是,当从我的 shell(bash) 中尝试它时,我没有看到任何结果。当我从 shell 运行这些时,似乎没有任何变化。我这里哪里出错了?

答案1

我将使用awk状态机来实现此目的。我使用标志blankblock来指示空行和块

awk '
    /^$/ { blank++ }                                            # Blank line
    blank && /^>/ { blank=0; block++; print "<blockquote>" }    # First ">" line after blank
    block && blank { block=0; print "</blockquote>" }           # First blank after ">"
    /^./ { blank=0 }                                            # Non-blank line
    { print }                                                   # Print the input data
'

测试数据

One blank line below

> This is a text
> This is another line of text

One blank line above

------------------------------------

One blank line below
> This is a text
> This is another line of text
One blank line above

------------------------------------

One blank line below

> This is a text

> This is another line of text

One blank line above

输出

One blank line below

<blockquote>
> This is a text
> This is another line of text
</blockquote>

One blank line above

------------------------------------

One blank line below
> This is a text
> This is another line of text
One blank line above

------------------------------------

One blank line below

<blockquote>
> This is a text
</blockquote>

<blockquote>
> This is another line of text
</blockquote>

One blank line above

相关内容