34.10 Referencing Portions of a Search String
, the substitution command provides metacharacters
to select any individual portion of a string that is matched and
recall it in the replacement string.
A pair of escaped parentheses are used in
to enclose any part of a regular expression and save it
for recall. Up to nine "saves" are permitted for
a single line.
For example, to embolden the section numbers when they appeared as a cross reference, we could write the following substitution:
s/\(See Section \)\([1-9][0-9]*\.[1-9][0-9]*\)/\1\\fB\2\\fP/
Two pairs of escaped parentheses are specified. The first
captures "See Section" (because this is a fixed string, it could
have been simply retyped in the replacement string). The second
captures the section number.
The replacement string recalls the first saved substring as
We can use a similar technique to match parts of a line and swap them. For instance, let's say there are two parts of a line separated by a colon. We can match each part, putting them within escaped parentheses and swapping them in the replacement:
The larger point is that you can recall a saved substring in any order, and multiple times.
Articles 13.11 , 14.9 , 16.6 , 18.9 , 45.30 , and 51.3 have examples.
- from O'Reilly & Associates' sed & awk , Chapter 5