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 registera:s/old/new/g-- substitute all occurrences ofoldwithnewon the current line<CR>-- press Enter to execute the commandj-- move to the next lineq-- 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:
- Record:
qa:s/http:/https:/g<CR>A # updated<Esc>jq - This substitutes on the current line, appends a comment, and moves down
- Run
10@ato 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.