[Chapter 34] 34.11 Search & Replacement: One Match Among Many
Author: Jerry Peek, Tim O'Reilly & Mike Loukides
Date: 1998-08-04T21:47:19Z

#

| Chapter 34 The sed Stream Editor |

## 34.11 Search & 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 tabs. 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:

>     Column1[TAB]Column2[TAB]Column3[TAB]Column4

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

>     Column1[TAB]Column2>Column3[TAB]Column4

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 numeric value is from 1 to 512.

- DD from O'Reilly & Associates' sed & awk, Chapter 5

34.10 Referencing Portions of a Search String |  | 34.12 Transformations on Text