How sed works
The sed program is a stream editor that receives its input from standard input, changes that input as directed by commands in a command file, and writes the resulting stream to standard output.
If you do not provide a command file and do not use any flags with the sed command, the sed program copies standard input to standard output without change. Input to the program comes from two sources:
| Program | Description |
|---|---|
| Input stream | A stream of ASCII characters either from one or more files or entered directly from the keyboard. This stream is the data to be edited. |
| Commands | A set of addresses and associated commands to be performed,
in the following general form: The parameters Line1 and Line2 are
called addresses. Addresses can be either patterns to match in the
input stream, or line numbers in the input stream. |
You can also enter editing commands along with the sed command by using the -e flag.
When sed edits, it reads the input stream one line at a time into an area in memory called the pattern space. When a line of data is in the pattern space, sed reads the command file and tries to match the addresses in the command file with characters in the pattern space. If it finds an address that matches something in the pattern space, sed then performs the command associated with that address on the part of the pattern space that matched the address. The result of that command changes the contents of the pattern space, and thus becomes the input for all following commands.
When sed has tried to match all addresses in the command file with the contents of the pattern space, it writes the final contents of the pattern space to standard output. Then it reads a new input line from standard input and starts the process over at the start of the command file.
Some editing commands change the way the process operates.
Flags used with the sed command can also change the operation of the command.