English 中文(简体)
Sed - Branches
  • 时间:2024-12-22

Stream Editor - Branches


Previous Page Next Page  

Branches can be created using the t command. The t command jumps to the label only if the previous substitute command was successful. Let us take the same example as in the previous chapter, but instead of printing a single hyphen(-), now we print four hyphens. The following example illustrates the usage of the t command.

[jerry]$ sed -n   
h;n;H;x 
s/
/, / 
:Loop 
/Paulo/s/^/-/ 
/----/!t Loop 
p  books.txt 

When the above code is executed, it will produce the following result.

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

In the above example, the first two commands are self-explanatory. The third command defines a label Loop. The fourth command prepends hyphen(-) if the pne contains the string "Paulo" and the t command repeats the procedure until there are four hyphens at the beginning of the pne.

To improve readabipty, each SED command is written on a separate pne. Otherwise, we can write a one-pner SED as follows:

[jerry]$ sed -n  h;n;H;x; s/
/, /; :Loop;/Paulo/s/^/-/; /----/!t Loop; p  books.txt 

When the above code is executed, it will produce the following result.

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
Advertisements