Quick Reference: sed

How sed operates:

Syntax of sed Commands

sed commands have the general form:

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

sed commands consist of addresses and editing commands. 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. Elements in [brackets] are optional; don't type the brackets.

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

[address][address]{ command1 command2 }

The left curly brace ({) is a command that starts a group of other sed commands. The group ends with a right curly brace (}). Commands within the braces may be spread across multiple lines, as shown above. Or commands may be on the same line, with a semicolon (;) after each command (including the last command on a line) - as in:

[address][address]{command1; ...commandN};

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 Regular Expressions (Pattern Matching). Additionally, n can be used to match any newline in the pattern space (resulting from the N command), but not the newline at the end of the pattern space. See article .

If the command specifies: Then it is applied to:
No address Each input line.
One address Any line matching the address. Some commands accept only one address: a, i, r, q, and =.
Two comma-separated addresses First matching line and all succeeding lines up to and including a line matching the second address. Repeat for each matching range in the text.
An address followed by ! All lines that do not match the address.

Examples

Substitute on all lines (all occurrences):

s/xx/yy/g

Delete lines containing BSD:

/BSD/d

Print the lines between each pair of BEGIN and END, inclusive:

/^BEGIN/,/^END/p

Delete any line that doesn't contain SAVE:

/SAVE/!d

Substitute on all lines, except between BEGIN and END:

/BEGIN/,/END/!s/xx/yy/g


Alphabetical Summary of sed Commands

- DG from Anonymous' UNIX tutorial (SVR4/Solaris)