How do I run a normal mode command on every line matching a pattern?
Answer
:g/pattern/normal dd
Explanation
The :g/pattern/normal {commands} command executes normal mode keystrokes on every line in the file that matches the given pattern. It combines the power of the global command (:g) with the :normal Ex command, letting you apply any normal mode editing sequence to a filtered set of lines.
How it works
:g/pattern/finds every line matching the regular expressionnormaltells Vim to execute the following text as if it were typed in normal modedd(or any other sequence) is the normal mode command to run on each matching line
Vim processes each matching line one at a time, positioning the cursor at the beginning of the line before executing the normal mode commands.
Examples
Delete all lines containing "console.log":
:g/console\.log/normal dd
Comment out all lines containing "TODO" (prepend // ):
:g/TODO/normal I//
Indent all lines containing "return":
:g/return/normal >>
Append a semicolon to every line containing a function call:
:g/()/normal A;
Tips
- Use
:g/pattern/normal @ato run a recorded macro on every matching line - Use
:v/pattern/normal ddto run the command on lines that do not match the pattern - The
:normalcommand does not process special keys like<Esc>written literally — use:normal!(with a bang) to ignore user mappings, or use:executewith escape sequences for special keys:
:g/pattern/execute "normal I// \<Esc>A;"
- The cursor is placed at column 1 of each matching line before the normal command runs
- You can limit the range:
:10,50g/pattern/normal ddonly affects lines 10 through 50 - This technique is often faster and more readable than writing a complex substitution with regex