In Vim, how do I apply a macro to a set of lines?

VimVim Macros

Vim Problem Overview


I have a file with a bunch of lines. I have recorded a macro that performs an operation on a single line. I want to repeat that macro on all of the remaining lines in the file. Is there a quick way to do this?

I tried Ctrl+Q, highlighted a set of lines, and pressed @@, but that didn't seem to do the trick.

Vim Solutions


Solution 1 - Vim

Use the normal command in Ex mode to execute the macro on multiple/all lines:

Execute the macro stored in register a on lines 5 through 10.

:5,10norm! @a

Execute the macro stored in register a on lines 5 through the end of the file.

:5,$norm! @a

Execute the macro stored in register a on all lines.

:%norm! @a

Execute the macro store in register a on all lines matching pattern.

:g/pattern/norm! @a

To execute the macro on visually selected lines, press V and the j or k until the desired region is selected. Then type :norm! @a and observe the that following input line is shown.

:'<,'>norm! @a

Enter :help normal in vim to read more.

Solution 2 - Vim

Use global to run the macro 'a' on all lines that contain 'pattern'

:g/pattern/normal! @a

For help, check: :help global.

Solution 3 - Vim

You can also do this:

In normal mode:

[number of times to apply the macro] @ [register]

For example:

1000@q

Apply the macro in register q to the next 1000 lines.

> Update: the accepted answer is a lot better > > Update: as @kevinliu pointed out, you likely want to end the macro with a j to go to the next line.

Solution 4 - Vim

There's also a plugin called RangeMacro, does exactly what you want! For everyone that can't guess by the name, what it does: it repeats a recorded macro for each line in a given range, no matter if by visual selection or by a :40,50 / :+10

See http://www.vim.org/scripts/script.php?script_id=3271

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJordan ParmerView Question on Stackoverflow
Solution 1 - VimJudge MaygardenView Answer on Stackoverflow
Solution 2 - VimSergioAraujoView Answer on Stackoverflow
Solution 3 - VimMax HeiberView Answer on Stackoverflow
Solution 4 - VimphuxView Answer on Stackoverflow