The Sed Editor

This section presents the following topics:

For more information, see the Nutshell Handbook sed & awk.

Command-line Syntax

  The syntax for invoking sed has two forms:

The first form allows you to specify an editing command on the command line, surrounded by single quotes. The second form allows you to specify a scriptfile, a file containing sed commands. If no files are specified, sed reads from standard input.

The following options are recognized:

Conceptual Overview

Sed is a non-interactive, or stream-oriented, editor. It interprets a script and performs the actions in the script. Sed is stream-oriented because, like many UNIX programs, input flows through the program and is directed to standard output. For example, sort is stream-oriented; VI is not. Sed’s input typically comes from a file but can be directed from the keyboard. Output goes to the screen by default but can be captured in a file instead.

Typical Uses of Sed Include:

 

Sed Operates as Follows:

Syntax of Sed Commands

Sed commands have the general form:

 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. address are described below.

 

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 Section 6. 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:

The command 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

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.

Examples

s/xx/yy/g

Substitute on all lines (all occurrences).

/BSD/d

Delete lines containing BSD.

/^BEGIN/,/^END/p

Print between 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.

 

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

 

Group Summary of Sed Commands

In the Lists below, the sed commands are grouped by function and are described tersely. Full descriptions, including syntax and examples can be found afterward in the alphabetical summary.

Basic Editing

a\ Append text after a line.

c\ Replace text (usually a text block).

i\ Insert text after a line.

d Delete lines.

s Make substitutions.

y Translate characters (like a UNIX tr).

Line Information

= Display line number of a line.

Display control characters in ASCII.

p Display the line.

 

Input/Output Processing

n Skip the current line and go to line below.

r Read another file's contents into the input.

w Write input lines to another file.

q Quit the sed script (no further output).

 

Yanking and Putting

h Copy into hold space; wipe out what's there.

H Copy into hold space; append to what's there.

g Get the hold space back; wipe out the destination line.

G Get the hold space back; append on line below.

x Exchange contents of hold space and pattern space.

Branching Commands

b Branch to label or to end of script.

t Same as b, but branch only after substitution.

:label Label branched to by t or b.

Multi-line Input Processing

N Read another line of input (creates embedded newline).

D Delete up to the embedded newline.

P Print up to the embedded newline.

 

Alphabetical Summary of Sed Commands

#

Begin a comment in a sed script. Valid only as the first character of the first line.

:label

Label a line in the script for the transfer of control by b or t. label may contain up to seven characters.

[/pattern/]=

Write to standard output the line number of each line addressed by pattern.

[address]a\

text

Append text following each line matched by address. If text goes over more than one line, newlines must be "hidden" by preceding them with a backslash. The text will be terminated by the first newline that is not hidden in this way. The text is not available in the pattern space, and subsequent commands cannot be applied to it. The results of this command are sent to standard output when the list of editing commands is finished, regardless of what happens to the current line in the pattern space.

Example

[address1][,address2]b[label]

Transfer control unconditionally to :label elsewhere in script. That is the command following the label is the next command applied to the current line. If no label is specified, control falls through to the end of the script, so no more commands are applied to the current line.

 

Example

[address1][,address2]c\

text

Replace the lines selected by the address with text. When a range of lines is specified, all lines as a group are replace by a single copy of text. The newline following each line of text must be escaped by a backslash, except the last line. The contents of the pattern space are, in effect, deleted and no subsequent editing commands can be applied to it (or text).

Example

[address1][,addresss2]d

Delete the addressed line (or lines from the pattern space. Thus, the line is not passed to standard output. A new line of input is read, and editing resumes with the first command in the script.

Example

[address1][,address2]D

Delete first part (up to embedded newline) of multi-line pattern space created by N command and resume editing with the first command in script. If this command empties the pattern space, then a new line of input is read, as if the d had been executed.

Example

[address1][,address2]g

Paste the contents of the hold space (see h or H command) back into the pattern space, wiping out the previous contents of the pattern space. The example shows a simple way to copy lines.

Example

This script collects all lines containing the word Item: and copies them to a place marker later in the file. The place marker is overwritten.

[address1][,address2]G

Same as g, except that the hold space is pasted below the address instead of overwriting it. The example shows a simple way to "cut and paste" lines.

Example

This script collects all lines containing the word Item: and moves them after a place marker later in the file. The original Item: lines are deleted.

[address1][,address2]h

 

Copy the pattern space into the hold space, a special temporary buffer. The previous contents of the hold space are obliterated. You can use h to save a line before editing it.

Example

[address1][,address2]H

Append the contents of the pattern space (preceded by a newline) to the contents of the hold space. Even if the hold space is empty, H still appends a newline. H is like an incremental copy. See examples under g and G.

[address1]i\
text

Insert text before each line matched by address. (See a for details on text.)

Example

[address1[],address2]1

List the contents of the pattern space, showing nonprinting characters as ASCII codes. Long lines are wrapped.

[address1][,address2]n

Read next line of input into pattern space. The current lines is sent to standard output, and the next line becomes the current line. Control passes to the command following n instead of resuming at the top of the script.

Example

[address1][,address2]N

Append next input line to contents of pattern space; the two lines are separated by an embedded newline. (This command is designed to allow pattern matches across two lines.) Using \n to match the embedded newline, you can match patterns across multiple lines. See example under D.

Examples

Like previous example, but print .NH line as well as header title:

Join two lines (replace newline with space):

[address1][,address2]p

Print the address lines(s). Unless the -n command-line option is used, this command will cause duplicate lines to be output. Also, it is typically used before commands that change flow control (d, N, b) and that might prevent the current line from being output. See examples under h, n, and N.

[address1][,address2]P

Print first part (up to embedded newline) of multi-line pattern created by n command. Same as p if N has be been applied to a line.

Example

The following script changes argument c, regardless of whether it appears on the same line as the function name:

[address]q

Quit when address is encountered. The addressed line is first written to output (if default output is not suppressed), along with any text appended to it by previous a or r commands.

Example

Delete everything after the addressed line:

Print only the first 50 lines of a file:

[address]r file

Read contents of file and append after the contents of the pattern space. Exactly one space must be put between the r and the filename.

Example

/The list of items follow:/r item_file

[addres1][,address2]s/pattern/replacement/[flags]

Substitute replacement for pattern on each addressed line. If pattern addresses are used, the pattern // represents the last pattern address specified. The following flags can be specified:

Test if any substitutions have been made on addressed line, and if so, branch to line marked by :label. (See b and :.) If label is not specified, control falls through to bottom of script. The t command is like a case statement in the C programming language or the shell programming languages. You test each case: when it's true, you exit the construct.

Example

Suppose you want to fill empty fields of a database. You have this:

You want this:

You need to test the number of fields already there. Here’s the script (fields are tab-separated):

[address1][,address2]w file

Append contents of pattern space to file. This action occurs when the command is encountered rather than when the pattern space is output. Exactly one space must separate the w and the filename. A maximum of ten different files can be opened in a script. This command will create the file if it does not exist; if the file exists, its contents will be overwritten each time the script is executed. Multiple write commands that direct output to the same file append to the end of the file.

Example

[address1][,address2]x

Exchange contents of the pattern space with the contents of the hold space. See h for an example.

[address1][,address2]y/abc/xyz/

Translate characters. Change every instance of a to x, b to y, i to z, etc.

Example

More Examples

>sed /^$/d deletes all blank lines from a stream