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

我們已經討論了在前面的章節中的第一個命令。第三個命令定義一個標籤迴圈。第四命令上前置的連字元( - ),如果該行包含字串“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

上一篇: Sed迴圈 下一篇: sed模式緩衝區