Applying Commands in a Script
Combining a series of edits in a script can have unexpected results. You might not think of the consequences one edit can have on another. New users typically think that sed applies an individual editing command to all lines of input before applying the next editing command. But the opposite is true. Sed applies the entire script to the first input line before reading the second input line and applying the editing script to it. Because sed is always working with the latest version of the original line, any edit that is made changes the line for subsequent commands. Sed doesn’t retain the original. This means that a pattern that might have matched the original input line may no longer match the line after an edit has been made.
Let’s look at an example that uses the substitute command. Suppose someone quickly wrote the following script to change “pig” to “cow” and “cow” to “horse”:
s/pig/cow/g s/cow/horse/g
What do you think happened? Try it on a sample file. We’ll discuss what happened later, after we look at how sed works.
The Pattern Space
Sed maintains a pattern space, a workspace or temporary buffer where a single line of input is held while the editing commands are applied.[1] The transformation of the pattern space by a two-line script is shown in Figure 4.1. It changes “The Unix System” to “The UNIX Operating System.”
Initially, the pattern space contains a copy of a single input line. In Figure 4.1, that line is “The Unix System.” The normal flow ...