UNIX Power Tools

UNIX Power ToolsSearch this book
Previous: 34.19 Making Edits Everywhere Except... Chapter 34
The sed Stream Editor
Next: 34.21 Uses of the sed Quit Command
 

34.20 The sed Test Command

The test command, t, branches to a label (or the end of the script) if a successful substitution has been made on the currently addressed line. It implies a conditional branch. Its syntax is as follows:

[address]t[label]

If no label is supplied, control falls through to the end of the script. If label is supplied, then execution resumes at the line following the label.

Let's look at a spelling corrector written by Greg Ubben. The script fixes common (in this example, silly) spelling goofs; the t command tells about corrections that were made:

h
s/seperate/separate/g
s/compooter/computer/g
s/said editor/sed editor/g
s/lable/label/g
t changed
b
: changed
p
g
s/.*/[WAS: &]/
t

First, h (34.13) holds a copy of the current input line. Then, if any of the four substitutions succeed, the command t changed branches to the corresponding label (: changed) at the end of the script. Otherwise, if no s succeeded, the b command restarts the script on the next line (as always in sed, the input line is printed before the script re-starts).

After the label, the script prints the current input line (the line with a spelling error - which, by now, has been corrected). Then g (34.13) gets the original uncorrected line. An s command brackets that line [WAS: xxx]. Here's some sample output:

$ sed -f sedscr afile
This is a separate test.
[WAS: This is a seperate test.]
I put a label on my computer!
[WAS: I put a lable on my compooter!]
That's all for now.

The final t in the script is a work-around for a bug in some versions of sed. Greg says "The t flag is supposed to be reset after either the t command is executed or a new line of input is read, but some versions of sed don't reset it on a new line of input. So I added a do-nothing t to make sure it's reset after the previous always-true s///." Try the script without the extra t; if adding it makes the script work right, your sed has the bug and you might try a new version, like GNU gsed.

- JP, DD


Previous: 34.19 Making Edits Everywhere Except... UNIX Power ToolsNext: 34.21 Uses of the sed Quit Command
34.19 Making Edits Everywhere Except... Book Index34.21 Uses of the sed Quit Command

The UNIX CD Bookshelf NavigationThe UNIX CD BookshelfUNIX Power ToolsUNIX in a NutshellLearning the vi Editorsed & awkLearning the Korn ShellLearning the UNIX Operating System