home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Unix Power ToolsUnix Power ToolsSearch this book

34.12. Search and Replacement: One Match Among Many

One of the more unusual options of sed's substitution command is the numeric flag that allows you to point to one particular match when there are many possible matches on a particular line. It is used where a pattern repeats itself on a line and the replacement must be made for only one of those occurrences by position. For instance, a line, perhaps containing tbl input, might contain multiple tab characters. Let's say that there are three tabs per line, and you'd like to replace the second tab with >. The following substitute command would do it:

s/TAB/>/2

TAB represents an actual tab character, which is otherwise invisible on the screen. If the input is a one-line file such as the following:

Column1TABColumn2TABColumn3TABColumn4

the output produced by running the script on this file will be:

Column1TABColumn2>Column3TABColumn4

Note that without the numeric flag, the substitute command would replace only the first tab. (Therefore, 1 can be considered the default numeric flag.) The range of the allowed numeric value is from 1 to 512, though this may be implementation-dependent.

-- DD



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.