UNIX in a Nutshell: System V Edition

UNIX in a Nutshell: System V EditionSearch this book
Previous: 10.2 Command-Line SyntaxChapter 10
The sed Editor
Next: 10.4 Group Summary of sed Commands
 

10.3 Syntax of sed Commands

sed commands have the general form:

[address[,address]][!]command [arguments]

sed copies each line of input into the pattern space. sed instructions consist of addresses and editing commands. If the address of the command matches the line in the pattern space, the command is applied to that line. If a command has no address, it is applied to each input line. If a command changes the contents of the pattern space, subsequent commands and addresses are applied to the current line in the pattern space, not the original input line.

commands consist of a single letter or symbol; they are described later, alphabetically and by group. arguments include the label supplied to b or t, the filename supplied to r or w, and the substitution flags for s. addresses are described below.

10.3.1 Pattern Addressing

A sed command can specify zero, one, or two addresses. An address can be a line number, the symbol $ (for last line), or a regular expression enclosed in slashes (/pattern/). Regular expressions are described in Chapter 6, Pattern Matching. Additionally, \n matches any newline in the pattern space (resulting from the N command), but not the newline at the end of the pattern space.

If the Command Specifies:Then the Command is Applied to:
No addressEach input line.
One address

Any line matching the address. Some commands accept only one address: a, i, r, q, and =.

Two comma-separated

First matching line and all succeeding lines up to and including a line matching the second address.

addresses
An address followed by !All lines that do not match the address.

10.3.2 Examples

s/xx/yy/gSubstitute on all lines (all occurrences).
/BSD/dDelete lines containing BSD.
/^BEGIN/,/^END/pPrint between BEGIN and END, inclusive.
/SAVE/!dDelete any line that doesn't contain SAVE.
/BEGIN/,/END/!s/xx/yy/gSubstitute on all lines, except between BEGIN and END.

Braces ({}) are used in sed to nest one address inside another or to apply multiple commands at the same address.

[/pattern/[,/pattern/]]{
command1
command2
}

The opening curly brace must end its line, and the closing curly brace must be on a line by itself. Be sure there are no spaces after the braces.


Previous: 10.2 Command-Line SyntaxUNIX in a Nutshell: System V EditionNext: 10.4 Group Summary of sed Commands
10.2 Command-Line SyntaxBook Index10.4 Group Summary of sed Commands

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