About the Syntax of sed Commands
Comment
Substitution
Delete
Append, Insert, and Change
List
Transform
Print
Print Line Number
Next
Reading and Writing Files
Quit
The sed command set consists of 25 commands. In this chapter, we introduce four new editing commands: d (delete), a (append), i (insert), and c (change). We also look at ways to change the flow control (i.e., determine which command is executed next) within a script.
Before looking at individual commands, there are a couple of points to review about the syntax of all sed commands. We covered most of this material in the previous chapter.
A line address is optional with any command. It can be a pattern described as a regular expression surrounded by slashes, a line number, or a line-addressing symbol. Most sed commands can accept two comma-separated addresses that indicate a range of lines. For these commands, our convention is to specify:
[address]command
A few commands accept only a single line address. They cannot be applied to a range of lines. The convention for them is:
[line-address]command
Remember also that commands can be grouped at the same address by surrounding the list of commands in braces:
address { command1 command2 command3 }
The first command can be placed on the same line with the opening brace but the closing brace must appear on its own line. Each command can have its own address and multiple levels of grouping are permitted. Also, as you can see from the indentation of the commands inside the braces, spaces, and tabs at the beginning of lines are permitted.
When sed is unable to understand a command, it prints the message "Command garbled." One subtle syntax error is adding a space after a command. This is not allowed; the end of a command must be at the end of the line.
Proof of this restriction is offered by an "undocumented" feature: multiple sed commands can be placed on the same line if each one is separated by a semicolon.[27] The following example is syntactically correct:
[27]Surprisingly, the use of semicolons to separate commands is not documented in the POSIX standard.
n;d
However, putting a space after the n command causes a syntax error. Putting a space before the d command is okay.
Placing multiple commands on the same line is highly discouraged because sed scripts are difficult enough to read even when each command is written on its own line. (Note that the change, insert, and append commands must be specified over multiple lines and cannot be specified on the same line.)
Copyright © 2003 O'Reilly & Associates. All rights reserved.