How do I run a command on every line matching a pattern?
Answer
:g/pattern/command
Explanation
The :g/pattern/command (global) command executes an Ex command on every line in the file that matches the given pattern. It is one of Vim's most powerful features, enabling complex batch edits with a single command.
How it works
:gis the global command/pattern/is a regular expression to match lines againstcommandis any Ex command to execute on each matching line
Vim scans the entire file, marks every line that matches the pattern, and then executes the command on each marked line in order.
Examples
Delete all lines containing "debug":
:g/debug/d
Yank all lines containing "TODO" into register a:
:g/TODO/yank A
Indent all lines containing "return":
:g/return/>
Move all lines containing "import" to the top of the file:
:g/import/m 0
The inverse: :v (vglobal)
Use :v/pattern/command to execute a command on every line that does not match the pattern. For example, delete all lines that do not contain "keep":
:v/keep/d
Tips
- Use
:g/pattern/normal @ato run a macro on every matching line - Use
:g/^$/dto delete all blank lines in a file - Use
:g/pattern/s/old/new/gto run a substitution only on lines matching a pattern - The global command supports ranges:
:10,50g/pattern/doperates only on lines 10–50 - Use
:g/pattern/pto print all matching lines without modifying anything (like a built-in grep) - Chain with
:normalto run normal-mode commands::g/TODO/normal I//comments out all TODO lines - The pattern uses Vim's regex syntax — use
\vfor "very magic" mode if you prefer Perl-like regex