流编辑器 - 分支

可以使用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