空の行とその下の行を次に置き換えます。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)にあるときはうまく機能しますが、シェルで試しても結果は見えません。シェルでこれを実行すると、何も変わらないようです。ここで私はどこで間違っていますか?

ベストアンサー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

おすすめ記事