Stream 编辑器 - 分支

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