
- Sed 教程
- Sed - 首頁
- Sed - 概述
- Sed - 環境
- Sed - 工作流
- Sed - 基本語法
- Sed - 迴圈
- Sed - 分支
- Sed - 正則表示式緩衝區
- Sed - 正則表示式範圍
- Sed - 基本命令
- Sed - 特殊字元
- Sed - 字串
- Sed - 管理正則表示式
- Sed - 正則表示式
- Sed - 實用食譜
- Sed 實用資源
- Sed - 快速指南
- Sed - 實用資源
- Sed - 討論
流編輯器 - 分支
可以使用 t 命令建立分支。當之前的替換命令成功時,t 命令才跳轉到標籤。讓我們舉出與前一章中相同的示例,但是現在我們不列印單個連字元 (-),而是列印四個連字元。以下示例說明了 t 命令的用法。
[jerry]$ sed -n ' h;n;H;x s/\n/, / :Loop /Paulo/s/^/-/ /----/!t Loop p' books.txt
當執行上述程式碼時,將產生以下結果。
A Storm of Swords, George R. R. Martin The Two Towers, J. R. R. Tolkien ----The Alchemist, Paulo Coelho The Fellowship of the Ring, J. R. R. Tolkien ----The Pilgrimage, Paulo Coelho A Game of Thrones, George R. R. Martin
在上述示例中,前兩個命令不言自明。第三個命令定義了一個標籤 Loop。如果行包含字串 "Paulo",則第四個命令會前置連字元 (-),而 t 命令會重複此過程,直到行首有四個連字元為止。
為了提高可讀性,每個 SED 命令都寫在單獨的一行中。否則,我們可以編寫一行 SED,如下所示
[jerry]$ sed -n 'h;n;H;x; s/\n/, /; :Loop;/Paulo/s/^/-/; /----/!t Loop; p' books.txt
當執行上述程式碼時,將產生以下結果。
A Storm of Swords, George R. R. Martin The Two Towers, J. R. R. Tolkien ----The Alchemist, Paulo Coelho The Fellowship of the Ring, J. R. R. Tolkien ----The Pilgrimage, Paulo Coelho A Game of Thrones, George R. R. Martin
廣告