Good Ol' sed

Hans de Vreught

Issue #60, April 1999

A nice little command to help you modify files.

When I started using UNIX in 1982, life in the computer world was fairly cruel. At that time, most programmers were still using line editors. The UNIX line editor, ed, was a relief in comparison with most line editors of other operating systems. Its sensible use of regular expressions was a blessing, and the fun part was that most UNIX tools used the same kind of regular expressions.

Although UNIX had virtual memory, the size of files that ed could handle was limited; disk space for memory was expensive. For large files, programmers had to resort to the stream editor, sed. sed reads its input line-after-line and performs its editing operations line-by-line. In sed, some commands allow use of multi-lines and so have a holding space, but in general, the amount of memory needed is small.

Besides the occasional one-line commands, I often wrote sed scripts. In those days, most system administration scripts were written in sed; awk was too slow and too big. The power demonstrated by those sed scripts was and still is quite amazing. They were true works of art—large and completely incomprehensible, but they got the job done.

Since sed is Turing-complete, it is as powerful as any programming language. Writing sed scripts that compute certain functions became a sport. Olaf Kirch, author of the Linux Network Administrator's Guide, says in his preface that he was proud to have written a prime number generator in sed. My pet script computes the Ackermann function and is available for anonymous download in the file ftp://ftp.linuxjournal.com/pub/lj/listings/issue60/2628.tgz along with a short explanation. It is just like programming in assembler.

Today, sed scripts are totally different—they are much simpler and are almost always one-liners. Most one-line sed commands (often included in Bourne scripts or used interactively in your shell of choice) modify or delete certain lines in a file. In some cases, you might still write sed scripts; however, the commands remain simple. Beside the two operations just mentioned, you also insert, append and change groups of lines as a block.

The advanced sed commands have disappeared (and I must say I'm glad). Although these advanced commands made sed powerful, they also made the scripts unreadable. Today, if you need to do something advanced, you would use awk or Perl.

Syntax

I will not describe every feature of sed. Instead, I will restrict myself to just those commands I regularly use. For more information on sed, the best resource is sed & awk by Dale Dougherty and Arnold Robbins (O'Reilly & Associates, 1997).

sed commands have the following form with no trailing spaces:

[address][,address][!]command[arguments]

I will begin with the address. An address is either a line number ($ for the last line) or a regular expression enclosed in slashes. The regular expressions are similar to the ones you see in vi (well, actually the ex part of vi): “.” (any character), “*” (any number of the immediately preceding regular expression), “[class]” (any character in class), “[^class]” (any character not in class), “^” (begining of line), “$” (end of line) and ''\'' (to escape characters where needed).

A range of lines can be specified by giving two addresses. The “!” after the address specification excludes that range from being processed. The most commonly used sed commands are “d” (delete) and “s” (substitute). The delete command is straightforward; it deletes any line that matches the entire address specification. Substitute is more interesting:

s/pattern/replacement/[g]

Basically, pattern is just a regular expression, but it has an odd feature: parts of the pattern can be stored in the replacement. The parts to keep must be enclosed within the characters “\(” and “\)”. In the replacement part, these stored parts can be used by specifying “\1”, “\2”, ..., “\9” (the first, the second, ..., and the ninth stored part). If the entire matched part is to be used, the “&” character is specified. The g (global) flag can be used to replace all occurrences of pattern by replacement.

Example

Assume we have a small table of two columns of numbers which we wish to swap:

s/\([0-9]*\) \([0-9]*\)/\2 \1/

The “[0-9]” part matches any digit and the “*” means that we allow any string of digits to be matched. Since “[0-9]*” is surrounded by “\(” and “\)”, it is stored. The first number of the line will be in “\1” and the second one will be in “\2”. In the replacement, they are recalled: first the second number, then the first. While it is a bit silly to write a file with just two lines, it is:

#!/usr/bin/sed -f
s/\([0-9]*\) \([0-9]*\)/\2 \1/
The -f flag means that the next argument is a file name containing a sed script. The way UNIX executes scripts, this means the script name will be used as an argument of -f (i.e., this file). Here is the one-line equivalent to be used at the command-line prompt in the shell (the -e flag specifies that the next argument is a sed command):
sed -e 's/\([0-9]*\) \([0-9]*\)/\2 \1/'
To perform more than one command on a particular range, use { and } to bracket a block of commands. Assume that in the header of the file, we wish to replace C++ style comments (“// ...”) with C style comments (“/* ... */”) and we wish to update the copyright year. A blank line appears after the header, as shown here:
// Copyright 1997 John Doe
// This is just an example.
...
We can use the following script (note the heavy escaping by the backslashes) to modify this header:
#!/usr/bin/sed -f"
1,/^$/{
s/Copyright 1997/Copyright 1998/
s/\/\/\(.*\)/\/*\1 *\//
}
These commands will modify the above header to be:
/* Copyright 1998 John Doe */
/* This is just an example. */
...

Insert, Append and Change

The next set of sed commands I often use in scripts are “i” (insert), “a” (append) and “c” (change). Insert and append are similar in that they both need an address either before which or after which text is inserted or appended. The text that is inserted follows on the next lines. All lines of the insert or append command must be “terminated” by a backslash except for the final line. For example:

1i\
This is a test\
to insert three lines\
at the beginning

With the change command, we can also specify a range of lines. If we specify only a single address, only that line will be changed; otherwise, the entire range will be modified.

Sometimes it is handy to read (“r”) from or write (“w”) to a file. In the case of a read, we can specify an address after which the file is to be read; in case of a write, we can specify one address or a range to be written to the file. For example, to write the lines preceding the first empty line to a file called foo, type the command:

#!/usr/bin/sed -f 1,/^$/w foo

sed is quite picky about spaces—only one space after “w” or “r” is allowed. Also, never use trailing spaces in sed commands; it doesn't like them and will give cryptic errors.

Next and Quit

The last two commands I will discuss are next (“n”) and quit (“q”). The next command takes a single address. After the specified line is output, the next line is read and the script resumes at the top. Normally, next commands are found within blocks of commands (i.e., within curly braces). The quit command also takes an address as an argument. When sed encounters quit, it immediately terminates the script without any further output.

Advanced

sed has several other commands, which can be considered advanced commands. You won't see them in modern sed scripts. Three sorts of advanced commands are available:

  • Conditional commands: in sed, you can define labels by preceding an identifier (7 characters at most) by a colon (“:”), then using the test (-t) command to jump to that label. Test checks if substitutions have been made.

  • Multi-line commands: sed has several commands that work with multiple lines, treating them as if they were a single line with embedded newlines. These commands make it hard to read sed scripts.

  • Holding space commands: sed is capable of saving and exchanging the current line with a separate line, called the holding space. What is true for multi-line commands is even more true for commands that handle the holding space—they truly make your scripts unreadable.

As I said earlier, use sed for one-line commands and simple scripts and awk and Perl for advanced commands. For those who wish to earn a virtual beer: write a sed script that computes the factorial function.

Hans de Vreught is a computer science researcher at Delft University of Technology. He has been using UNIX since 1982 (Linux since 0.99.13). He likes non-virtual Belgian beer and is a true globe trotter (already twice around the world). He can be reached at J.P.M.deVreught@cs.tudelft.nl.