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, 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 (Section 34.14) 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 restarts).
After the label, the script prints the current input line (the line with a spelling error -- which, by now, has been corrected). Then g (Section 34.14) 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 sed.
--JP and DD
Copyright © 2003 O'Reilly & Associates. All rights reserved.