How do I run normal mode edits on every line matching a pattern?
Answer
:g/pattern/normal A;
Explanation
The :global command combined with :normal lets you execute arbitrary normal mode keystrokes on every line that matches a pattern. This is incredibly powerful for batch editing — you can append text, delete words, change cases, or run any normal mode sequence on a filtered set of lines without recording a macro.
How it works
:g/pattern/— selects every line in the buffer matchingpatternnormal— tells Vim to execute the following text as normal mode keystrokesA;— moves to end of line (A) and appends a semicolon
The normal subcommand executes from the beginning of each matching line, as if you pressed those keys with the cursor at column 1.
Example
Suppose you have JavaScript lines missing semicolons:
const x = 1
let y = 2
// a comment
const z = 3
Running :g/^\(const\|let\)/normal A; produces:
const x = 1;
let y = 2;
// a comment
const z = 3;
Only the const and let lines are modified.
Tips
- Use
:g/pattern/normal 0f=lC new_valueto replace everything after=on matching lines - Add
!for special keys::g/pattern/exe "normal A\<C-r>a"to append registeracontents - Combine with
:v(inverse global) to edit lines that do NOT match::v/keep/normal dd