Stream Editor - Loops


SED facilitates branching and looping so that we can control the flow of execution.A loop in SED work like a goto statement. The SED can move to the line marked by the label and continue to execute the remaining commands.

\\ A name after colon(:) implies the label name.    


:label 
:start 
:end 
:up
  


NOTE : If we want to jump to a specific label, we can use the b command followed by the label name.

In our lfc.txt file, there are many entries from book authors and their titles. The following examples combines a book title and the name of its author to a one line seperated by a comma. Then it searches for the "Jawaharlal" pattern. If the pattern matches, it prints a hyphen (-) in front of the line, otherwise it jumps to the print label that prints the line.

Examples

$ sed -n ' 
h;n;H;x 
s/\n/, / 
/Jawaharlal/!b Print 
s/^/- / 
:Print 
p' lfc.txt

------------------
------------------

Walden, Henry David Thoreau
- The Discovery Of India, Jawaharlal Nehru
The Algebra of Infinite Justice, Arundhati Roy
Bookless in Baghdad, Shashi Tharoor
Adventures of Sherlock Holmes, Sir Arthur Conan Doyle


h;n;H;x and s/\n/, / :- combine the book title and its author separated by a comma(,).
/Jawaharlal/!b Print :- Print only when the pattern does not match.
:Print :- Print is just a label name.





Visit :


Discussion


* You must be logged in to add comment.