Lesson 8
Run Multiple sed Instructions
Objective: Apply several transformations in order during one input pass.
sed -e 's/:cat:/:feline:/' -e 's/:dog:/:canine:/' petchipEach -e adds an instruction to the script. For each input line, sed runs the instructions in the order supplied. The second instruction sees pattern space after the first instruction has modified it. This is one sed invocation, not a complete file pass per expression.
Using multiple -e options is a convenient way to build more complex editing logic while still processing the input only once. Because each expression is executed sequentially on the current pattern space, later substitutions can operate on text that has already been changed by earlier commands. This approach improves efficiency and readability by keeping related transformations together in a single sed invocation rather than chaining multiple sed commands through pipes.
Order changes the result
sed -e 's/$/:USA/' -e 's/8$/:Canada/' petchipThe first instruction appends :USA. The second instruction is reached but its 8$ pattern no longer matches. Saying that it never runs confuses execution with successful matching. Reversing instructions can change the output, so trace a sample line through every step.
Deletion ends the current cycle
sed -e '2,4d' -e '5s/:/#/g' petchip
Input lines 2 through 4 are discarded and do not reach the second instruction. Input line 5 still means the fifth original input record, Milo, even though earlier output lines were removed. Its colons are replaced with #. Line addresses refer to input processing, not newly numbered output.
Use a script file for longer programs
Save these two instructions in a new file named pets.sed:
s/:cat:/:feline:/
s/:dog:/:canine:/
sed -f pets.sed petchipA script file avoids layers of shell quoting and makes a transformation easier to review and version. These two simple instructions can also be separated with a semicolon in one quoted script. Do not assume every sed instruction has identical semicolon rules; text-insertion commands need particular care.
Practice two substitutions in the exercise. The exercise combines inserting a comma before the final three characters with replacing field separators.