UNIX Power Tools

UNIX Power ToolsSearch this book
Previous: 33.12 Versions of awk Chapter 34Next: 34.2 Invoking sed
 

34. The sed Stream Editor

Contents:
Two Things You Must Know About sed
Invoking sed
Testing and Using a sed Script: checksed, runsed
sed Addressing Basics
Order of Commands in a Script
One Thing at a Time
Delimiting a Regular Expression
Newlines in a sed Replacement
Referencing the Search String in a Replacement
Referencing Portions of a Search String
Search & Replacement: One Match Among Many
Transformations on Text
Hold Space: The Set-Aside Buffer
Transforming Part of a Line
Making Edits Across Line Boundaries
The Deliberate Scrivener
Searching for Patterns Split Across Lines
Multiline Delete
Making Edits Everywhere Except...
The sed Test Command
Uses of the sed Quit Command
Dangers of the sed Quit Command
sed Newlines, Quoting, and Backslashes in a Shell Script
Quick Reference: sed

34.1 Two Things You Must Know About sed

If you are already familiar with global edits in other editors like vi or ex, you know most of what you need to know to begin to use sed. There are two things, though, that make it very different:

  1. It doesn't change the file it edits. It is just what its name says: a "stream ed;;itor"-designed to take a stream of data from standard input (13.1) or a file, transform it, and pass it to standard output (13.1). If you want to edit a file, you have to write a shell wrapper (34.3) to capture standard output and write it back into your original file.

  2. sed commands are implicitly global. In an editor like ex, the command:

    s/old/new/

    will change "old" to "new" only on the current line unless you use the global command or various addressing symbols to apply it to additional lines. In sed, exactly the opposite is true. A command like the one above will be applied to all lines in a file. Addressing symbols are used to limit the extent of the match. (However, like ex, only the first occurrence of a pattern on a given line will be changed unless the g flag is added to the end of the substitution command.)

If all you want to do is make simple substitutions, you're ready to go. If you want to do more than that, sed has some unique and powerful commands.

This chapter makes no attempt to cover everything there is to know about sed. Article 34.24 contains a complete quick reference to sed commands, with many examples, because we use so many sed scripts elsewhere in this book, and we need a "dictionary" so beginners can interpret them. But for the most part, this chapter contains advice on working with sed and extended explanations of how to use some of its more difficult commands.

- TOR


Previous: 33.12 Versions of awk UNIX Power ToolsNext: 34.2 Invoking sed
33.12 Versions of awk Book Index34.2 Invoking sed

The UNIX CD Bookshelf NavigationThe UNIX CD BookshelfUNIX Power ToolsUNIX in a NutshellLearning the vi Editorsed & awkLearning the Korn ShellLearning the UNIX Operating System