For example, let's say I want to put a number before every line that starts with the word "Do". The command would look something like :%s/^(Do )/1. \1/, but what can I do so it will apply numbers consecutively instead of the same number each time?

Note that I'm well aware of the numerous ways to do this using macros and Ctrl-A, but for use in more complicated Ex-mode commands I would like to know the answer to exactly the title question.

For another example where a macro approach wouldn't be so easy, let's say I want to append a number to all instances of the word "Section", and have them consecutively numbered but restarting the count after each line that starts "Chapter". An Ex-mode command that can almost do this, save for actually incrementing the number to be added, is:

:g/^Chapter/;/^Chapter/-s/Section\zs/ 1/g

You can see that an easy method of incrementing numbers in the Ex-mode substitute command could be very useful.


This command does what you want:

:let i = 1|g/^Do/s/^/\=i/|let i = i + 1


  • let i = 1 initializes counter i,
  • g/^Do/s/^/\=i/ prepends i to each line starting with Do,
  • let i = i + 1 increments i.

The trick is that the incrementation happens before the next substitution.

--- edit ---

If we used a single substitution, the counter would only be incremented once, after everything is done.

Since we are performing multiple substitutions — one for each matching line — instead of a single one, the counter is correctly incremented before the next substitution.

| improve this answer | |
  • How can you put a dot after the number? \=i. is an invalid expression. – David Conrad Oct 13 '15 at 21:37
  • 2
    @DavidConrad, . becomes a concatenate operator in the \= expression. So s//\=i . '. '/ will append '. ' Check out :help expression-syntax. – Wildcard Oct 13 '15 at 23:35
  • incrementation happens after the substitution – Christian Brabandt Oct 14 '15 at 7:14
  • @ChristianBrabandt, oops I accidentally a word. – romainl Oct 14 '15 at 8:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.