vimtricks.wiki Concise Vim tricks, one at a time.

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 matching pattern
  • normal — tells Vim to execute the following text as normal mode keystrokes
  • A; — 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_value to replace everything after = on matching lines
  • Add ! for special keys: :g/pattern/exe "normal A\<C-r>a" to append register a contents
  • Combine with :v (inverse global) to edit lines that do NOT match: :v/keep/normal dd

Next

How do I return to normal mode from absolutely any mode in Vim?