Chapter 5. The GNU sed stream editor

Table of Contents

Introduction
What is sed?
sed commands
Interactive editing
Printing lines containing a pattern
Deleting lines of input containing a pattern
Ranges of lines
Find and replace with sed
Non-interactive editing
Reading sed commands from a file
Writing output files
Summary
Exercises

Abstract

At the end of this chapter you will know about the following topics:

  • What is sed?

  • Interactive use of sed

  • Regular expressions and stream editing

  • Using sed commands in scripts

[Note]This is an introduction

These explanations are far from complete and certainly not meant to be used as the definite user manual for sed. This chapter is only included in order to show some more interesting topics in the next chapters, and because every power user should have a basic knowledge of things that can be done with this editor.

For detailed information, refer to the sed info and man pages.

Introduction

What is sed?

A Stream EDitor is used to perform basic transformations on text read from a file or a pipe. The result is sent to standard output. The syntax for the sed command has no output file specification, but results can be saved to a file using output redirection. The editor does not modify the original input.

What distinguishes sed from other editors, such as vi and ed, is its ability to filter text that it gets from a pipeline feed. You do not need to interact with the editor while it is running; that is why sed is sometimes called a batch editor. This feature allows use of editing commands in scripts, greatly easing repetitive editing tasks. When facing replacement of text in a large number of files, sed is a great help.

sed commands

The sed program can perform text pattern substitutions and deletions using regular expressions, like the ones used with the grep command; see the section called “Examples using grep”.

The editing commands are similar to the ones used in the vi editor:

Table 5.1. Sed editing commands

CommandResult
a\Append text below current line.
c\Change text in the current line with new text.
dDelete text.
i\Insert text above current line.
pPrint text.
rRead a file.
sSearch and replace text.
wWrite to a file.

Apart from editing commands, you can give options to sed. An overview is in the table below:

Table 5.2. Sed options

OptionEffect
-e SCRIPTAdd the commands in SCRIPT to the set of commands to be run while processing the input.
-fAdd the commands contained in the file SCRIPT-FILE to the set of commands to be run while processing the input.
-nSilent mode.
-VPrint version information and exit.

The sed info pages contain more information; we only list the most frequently used commands and options here.