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

How do I record a macro that performs a search and replace on each line?

Answer

qa:s/old/new/g<CR>jq

Explanation

How it works

You can combine Ex commands like :s (substitute) with macro recording to create powerful repeatable find-and-replace operations that go beyond what a single :%s can do.

The command qa:s/old/new/g<CR>jq breaks down as:

  • qa -- start recording into register a
  • :s/old/new/g -- substitute all occurrences of old with new on the current line
  • <CR> -- press Enter to execute the command
  • j -- move to the next line
  • q -- stop recording

This is especially useful when you need to perform a substitution on some lines but also need additional editing operations in the same pass. You can add more commands between the substitution and the j movement.

The macro will fail and stop automatically on lines where the pattern is not found (unless you add the e flag: :s/old/new/ge), which can be either a feature or something to work around depending on your needs.

Example

Suppose you have a configuration file where you want to replace http with https and also add a comment at the end of each changed line:

  1. Record: qa:s/http:/https:/g<CR>A # updated<Esc>jq
  2. This substitutes on the current line, appends a comment, and moves down
  3. Run 10@a to process the next 10 lines

This approach gives you more flexibility than a global :%s because each iteration can include visual-mode selections, normal-mode edits, or multiple Ex commands.

Next

How do you yank a single word into a named register?