Good Ol' sed

 in
A nice little command to help you modify files.
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.

______________________

Webinar
One Click, Universal Protection: Implementing Centralized Security Policies on Linux Systems

As Linux continues to play an ever increasing role in corporate data centers and institutions, ensuring the integrity and protection of these systems must be a priority. With 60% of the world's websites and an increasing share of organization's mission-critical workloads running on Linux, failing to stop malware and other advanced threats on Linux can increasingly impact an organization's reputation and bottom line.

Learn More

Sponsored by Bit9

Webinar
Linux Backup and Recovery Webinar

Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.

In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.

Learn More

Sponsored by Storix