How do I run a normal mode command on every line matching a pattern?
Answer
:g/pattern/normal {cmd}
Explanation
Combining :global with :normal lets you run any normal-mode keystrokes on every line that matches a pattern. This is one of Vim's most powerful editing techniques, turning a single Ex command into a targeted batch operation across your entire file.
How it works
:g/pattern/— select all lines wherepatternmatchesnormal {cmd}— execute{cmd}as if you typed it in normal mode on each selected line- The cursor visits each matching line in order, running the keystrokes from the beginning of that line
<CR>,<Esc>, and other special keys can be entered with their literal notation
Example
Given a Python file with several function definitions, to add a blank line before each def:
:g/^def /normal O
This executes O (open a new line above) on every line starting with def .
To append a semicolon to every non-empty line:
:g/./normal A;
g/./ matches any non-blank line, and A; appends a semicolon.
Tips
- Use
\to enter a literal newline inside the:normalargument when needed - Combine with a range to limit scope:
:'<,'>g/TODO/normal dwoperates only on the visual selection - For multi-step sequences, record a macro first and then call it:
:g/pattern/normal @q - The inverse
:v/pattern/normal {cmd}runs the command on lines that do not match - Undo with a single
u— all edits from one:ginvocation are one undo block