Shell
使用 sed 將空行及其下方的一行替換為 <tag>
我有這樣的東西;
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 執行這些時,似乎什麼都沒有改變。我在哪裡錯了?
我會用
awk
狀態機來做這個。我使用標誌blank
並block
表示一個空行和一個塊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