Team LiB   Previous Section   Next Section

12.2 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. Some commands accept or expect arguments. Examples of 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 in the next section.

12.2.1 Pattern Addressing

A sed command can specify zero, one, or two addresses. An address can be a line number, an increment given as a starting line number and a step amount separated by a tilde (~), the symbol $ (for last line), or a regular expression enclosed in slashes (/pattern/). Regular expressions are described in Chapter 9. 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.

If the command specifies

Then the command is applied to

No address

Each input line.

One address

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

Two comma-separated addresses

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

An address followed by !

All lines that do not match the address.

12.2.1.1 Examples
s/xx/yy/g                Substitute on all lines (all occurrences)
/BSD/d                   Delete lines containing BSD
/^BEGIN/,/^END/p         Print  all lines between lines that begin with 
                        BEGIN and END, inclusive
/SAVE/!d                 Delete any line that doesn't contain SAVE
/BEGIN/,/END/!s/xx/yy/g  Substitute on all lines, except between BEGIN and END
1~2 p                    Print all odd numbered lines
2~3 d                    Delete every third line beginning with the second.

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 opening curly brace must end a line, and the closing curly brace must be on a line by itself. Be sure there are no blank spaces after the braces.

    Team LiB   Previous Section   Next Section