sed: Execution Cycle

1 
1 6.1 How 'sed' Works
1 ===================
1 
1 'sed' maintains two data buffers: the active _pattern_ space, and the
1 auxiliary _hold_ space.  Both are initially empty.
1 
1    'sed' operates by performing the following cycle on each line of
1 input: first, 'sed' reads one line from the input stream, removes any
1 trailing newline, and places it in the pattern space.  Then commands are
1 executed; each command can have an address associated to it: addresses
1 are a kind of condition code, and a command is only executed if the
1 condition is verified before the command is to be executed.
1 
1    When the end of the script is reached, unless the '-n' option is in
1 use, the contents of pattern space are printed out to the output stream,
1 adding back the trailing newline if it was removed.(1)  Then the next
1 cycle starts for the next input line.
1 
1    Unless special commands (like 'D') are used, the pattern space is
1 deleted between two cycles.  The hold space, on the other hand, keeps
1 its data between cycles (see commands 'h', 'H', 'x', 'g', 'G' to move
1 data between both buffers).
1 
1    ---------- Footnotes ----------
1 
1    (1) Actually, if 'sed' prints a line without the terminating newline,
1 it will nevertheless print the missing newline as soon as more text is
1 sent to the same output stream, which gives the "least expected
1 surprise" even though it does not make commands like 'sed -n p' exactly
1 identical to 'cat'.
1