You can move blocks of text delimited by patterns (30.9). For example, assume you have a 150-page reference manual. All references pages are organized into three paragraphs with the same three headings: SYNTAX, DESCRIPTION, and PARAMETERS. A sample of one reference page follows:
.Rh 0 "Get status of named file" "STAT" .Rh "SYNTAX" .nf integer*4 stat, retval integer*4 status(11) character*123 filename ... retval = stat (filename, status) .fi .Rh "DESCRIPTION" Writes the fields of a system data structure into the status array. These fields contain (among other things) information about the file's location, access privileges, owner, and time of last modification. .Rh "PARAMETERS" .IP "\fBfilename\fR" 15n A character string variable or constant containing the UNIX pathname for the file whose status you want to retrieve. You can give the ...
Suppose that it is decided to move the SYNTAX paragraph below the DESCRIPTION paragraph. Using pattern matching, you can move blocks of text on all 150 pages with one command!
:g/SYNTAX/,/DESCRIPTION/-1 mo /PARAMETERS/-1
This command operates on the block of
text between the line containing the word SYNTAX and the line just
before the word DESCRIPTION (/DESCRIPTION/-1
).
The block is moved (using mo
)
to the line just before PARAMETERS
(/PARAMETERS/-1
).
Note that ex can place text only below the line specified.
To tell ex to place text above a line, you first have to
move up a line with -1
, and then place your text below.
In a case like this, one command saves literally hours of work.
(This is a real-life example - we once used a pattern match like this
to rearrange a reference manual containing hundreds of pages.)
Block definition by patterns can be used equally well with other ex commands. For example, if you wanted to delete all DESCRIPTION paragraphs in the reference chapter, you could enter:
:g/DESCRIPTION/,/PARAMETERS/-1d
This very powerful kind of change is implicit in ex's line addressing syntax, but it is not readily apparent even to experienced users. For this reason, whenever you are faced with a complex, repetitive editing task, take the time to analyze the problem and find out if you can apply pattern-matching tools to do the job.
- from O'Reilly & Associates' Learning the vi Editor, Chapter 6