Sed tutorial

How Sed works –

Whenever we think of sed we have to think about two things:
1. Active Pattern space. 2. Auxiliary Hold space.
Both are initially empty.

Processing Steps:

  1. sed reads one input line at a time.
  2. Stores them in pattern space
  3. Execute the commands on the pattern space [Based on the address/conditions specified]
  4. Write the pattern space to the output

The above steps continue for the next line till the last line of the file. The most important thing to note is the command gets executed only on pattern space and not on hold space.
During cycle1 – Line 1 is read from the input file and stored into pattern space. The hold space will be empty.

During cycle2 – Line 2 is read from the input file and stored into pattern space and Line 1 will be stored into hold space.

This continues till the end of the file.

During last cycle – Last line will be in pattern space and lastline-1 line will be in hold space.

Though this is the default behavior we have commands to alter the pattern space or hold space.

To start with lets understand this default behavior of sed by the following example.