Shell Practice: Introduction to the sed stream editor

Slashdot it! Delicious Share on Facebook Tweet! Digg!
Dmitriy Sladkov, 123RF.com

Dmitriy Sladkov, 123RF.com

Quick Edit

With sed, you can edit text data without an interactive user interface, using pipes or input redirection. Sed lets you execute extensive editing commands on a single line.

The sed stream editor [1] automates many repetitive operations, especially effectively inside a shell script. You can use regular expressions (regex) to provide a "nature" of the string. In this article, I'll start with the program screen output. If you want to participate and practice, simply type the text files in an editor of your choice.

Sed Commands

The program calls up and accepts commands from virtually anywhere. You can pass commands directly or read them in from a separate file. The data can be piped, redirected, or input from a text file. The output can be sent to the screen (usually stdout ), through a pipe to the next command, or redirected to a destination file. With sed itself, no files are ever overwritten! The "Sed Call Options" box has the details. To resolve shell variables, you sometimes need to substitute the ' character with the " character.

Sed Call Options

Sed simply reads the text file and returns the results through stdout:

sed [COMMAND] [TEXTFILE]

Same with input redirection:

sed [COMMAND] < [TEXTFILE]

Inclusion of sed in one or more pipes:

[PROGRAM1] | sed [COMMAND] | ......

Commands stored in a separate file and read in:

... sed -f [SCRIPT] .....

Output of sed redirected to a text file, but omitting error messages:

... sed [COMMAND] > [TARGETFILE]

The same, but including error messages into the target file:

... sed [COMMAND] > [TARGETFILE] 2>&1

Syntax

The basic syntax structure is shown in Figure 1. You'll notice for all locations where the editing commands should be used that addressing is required. You can provide many addresses as long as doing so doesn't affect clarity. If you want to change "everything except," you can negate the addressing with the ! character.

Figure 1: Sed syntax structure.

You can add multiple commands on one command line to sed as follows:

sed -e 'command1' -e 'command2' ... -e 'commandN' ....

Or, you can add these commands in a script file.

Buy this article as PDF

Express-Checkout as PDF

Pages: 6

Price $0.99
(incl. VAT)

Buy Ubuntu User

SINGLE ISSUES
 
SUBSCRIPTIONS
 
TABLET & SMARTPHONE APPS
Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content