How do I run a global command only on lines within a visual selection?
Answer
:'<,'>g/pattern/command
Explanation
How it works
The :g (global) command is one of Vim's most powerful features. It matches lines by a pattern and runs an Ex command on each matching line. By combining it with a visual selection range, you restrict its operation to only the selected lines.
The syntax is:
:'<,'>g/pattern/command
'<,'>- The visual selection range (auto-filled when pressing:in visual mode)g/pattern/- Match lines containingpatterncommand- The Ex command to run on each matching line
Common use cases:
:'<,'>g/DEBUG/d- Delete all lines containing "DEBUG" in the selection:'<,'>g/^$/d- Delete all blank lines in the selection:'<,'>g/TODO/normal A (DONE)- Append " (DONE)" to lines containing "TODO":'<,'>g!/important/d- Delete lines NOT containing "important" (inverse match withg!orv):'<,'>g/error/s/warn/error/g- On lines matching "error", run a substitution
The inverse variant :v/pattern/command (or :g!/pattern/command) runs the command on lines that do NOT match the pattern.
Example
Given this log file, with lines 2-6 selected:
[INFO] Starting app
[DEBUG] Loading config
[INFO] Config loaded
[DEBUG] Connecting to DB
[INFO] Connected
[DEBUG] Running query
[INFO] Shutdown
- Select lines 2 through 6 with
V4j - Type
:'<,'>g/DEBUG/dand press Enter
Result:
[INFO] Starting app
[INFO] Config loaded
[INFO] Connected
[INFO] Shutdown
Only DEBUG lines within the selection were removed. Lines outside the selection were untouched, including the first and last INFO lines.