
- Sed Tutorial
- Sed - Home
- Sed - Overview
- Sed - Environment
- Sed - Workflow
- Sed - Basic Syntax
- Sed - Loops
- Sed - Branches
- Sed - Pattern Buffer
- Sed - Pattern Range
- Sed - Basic Commands
- Sed - Special Characters
- Sed - Strings
- Sed - Managing Patterns
- Sed - Regular Expressions
- Sed - Useful Recipes
- Sed Useful Resources
- Sed - Quick Guide
- Sed - Useful Resources
- Sed - Discussion
Stream Editor - Branches
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/\n/, / :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 line contains the string "Paulo" and the t command repeats the procedure until there are four hyphens at the beginning of the line.
To improve readability, each SED command is written on a separate line. Otherwise, we can write a one-liner SED as follows:
[jerry]$ sed -n 'h;n;H;x; s/\n/, /; :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