How do I restrict the :global command to operate on only a portion of the file?
Answer
:[range]g/pattern/command
Explanation
The :global command accepts an optional line range prefix that restricts which lines it even considers matching. Without a range it applies to the entire file, but with a range like :1,50g/pattern/d it only searches and acts within lines 1–50. This is essential when working with structured files where you need scoped operations on a defined section.
How it works
[range]— Any valid Ex range: absolute lines (:10,50), marks (:'a,'b), relative offsets (:.,.+20), or pattern boundaries (:/start/,/end/).g/pattern/— The global command's match pattern, applied only within the specified range.command— Any Ex command to execute on each matched line.
Without a range, :g defaults to 1,$ (the entire file). Specifying a range narrows that scope.
Example
Delete all blank lines, but only within the first 40 lines:
:1,40g/^$/d
Add a trailing semicolon to every return statement, but only inside a function demarcated by marks a and b:
:'a,'bg/\breturn\b/s/$/;/
Tips
- Visual selection works as a range:
:'<,'>g/TODO/ddeletes TODO lines only within the selection. - The inverse command
:v(:g!) accepts a range the same way::1,20v/./ddeletes empty lines only in lines 1–20. - Pattern-bounded ranges work well for section scoping:
:/^## Section/,/^## /g/^-/ddeletes bullet lines within a specific markdown section.