Shell

使用 sed 將空行及其下方的一行替換為 <tag>

  • April 14, 2021

我有這樣的東西;

One blank line below

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

One blank line above

試圖得到這樣的東西;

One blank line below

&lt;blockquote&gt;
> This is a text
> This is another line of text
&lt;/blockquote&gt;

One blank line above

試過這個;

sed 's/^\n\(&gt;\)/\r&lt;blockquote&gt;\r\1/g' test.txt

and

sed 's/^\(&gt;.*\)\n$/\1\r&lt;\/blockquote&gt;\r/g' test.txt

當我在 vim (8.1) 中時,這些正則表達式對我來說工作得很好,但是,當我從我的 shell(bash) 中嘗試它時,我沒有看到任何結果。當我從 shell 執行這些時,似乎什麼都沒有改變。我在哪裡錯了?

我會用awk狀態機來做這個。我使用標誌blankblock表示一個空行和一個塊

awk '
   /^$/ { blank++ }                                            # Blank line
   blank && /^&gt;/ { blank=0; block++; print "&lt;blockquote&gt;" }    # First "&gt;" line after blank
   block && blank { block=0; print "&lt;/blockquote&gt;" }           # First blank after "&gt;"
   /^./ { 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

&lt;blockquote&gt;
> This is a text
> This is another line of text
&lt;/blockquote&gt;

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

&lt;blockquote&gt;
> This is a text
&lt;/blockquote&gt;

&lt;blockquote&gt;
> This is another line of text
&lt;/blockquote&gt;

One blank line above

引用自:https://unix.stackexchange.com/questions/645108