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