4

I would like to apply macro a to a set of lines. For consecutive lines, this can be done by

:5,10norm! @a

(https://stackoverflow.com/questions/390174/in-vim-how-do-i-apply-a-macro-to-a-set-of-lines).

How to do it for every n-th line from my current cursor position?

2 Answers 2

9

How about writing a 2nd macro that moves down n lines and then executes @a? Using a mark you can easily jump back to your original position.

E.g., having defined your macro in register a, press qb to record in register b, press 5j to go to line 6, press @a to execute a and then q to quit recording. Using 9@b will then execute macro a on every 5th line, i.e. lines 11, 16, 21,..., up to line 51. Since j will fail at the end of the file, simpy use 1000@b for the whole file... adjust numbers as needed.

1
  • I was going to write an answer using a recursive macro (with basically the same logic), but this is better in every way so I'll just +1 this instead
    – evilsoup
    Commented Dec 11, 2015 at 20:59
3

Something like this:

  1. record current line number and n in some variables:

    :let c=line('.')
    :let n=2
    
  2. conditionally run the macro from your a register on every n-th line after the cursor:

    :g/^/if line('.') > c &&  (line('.') - c) % n == 0 | norm! @a
    

I also believe that it would be easier to alter the macro instead (to jump n lines below as its first or last operation).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.