43

I have a prepared statement in java that i am adding an argument to the front of. Long story short, I have to take a ton of set methods and increment their first argument by 1.

I'd like a quick way to do a search and replace matching all numbers, and then increment them by one.

3 Answers 3

68

Figured it out.

%s/\d\+/\=(submatch(0)+1)/g

http://vim.wikia.com/wiki/Using_an_expression_in_substitute_command

3
  • 9
    yup. Shouldn't need the parens around the whole expression, though. \=submatch(0)+1 should do the trick.
    – Mark Reed
    May 2, 2012 at 20:16
  • Wow, those \= substitutions really kick ass... That's what I love vim for: You get all those general, and simple to use tools, and can freely combine them to great effect. Unix principle at its best :-) May 15, 2019 at 12:28
  • 4
    I also wanted to mention how it would be used with a capture group: %s/int i = \(\d\+\);/\='int i = '.(submatch(1)+1).';'/g
    – mVChr
    Feb 19, 2020 at 21:36
17

The only regex you need to know is \d.

:g/\d/exe "normal! \<C-A>"
5
  • 3
    How do you make this global (like the g modifier for :s). Also, you need to escape your +
    – user606723
    May 2, 2012 at 20:21
  • @user606723 :g is by definition global
    – Ben Hughes
    May 12, 2013 at 23:50
  • This subtly answers the question even better because only the first number on the line is incremented (the first arg as mentioned in the question), whereas the accepted answer will increment all numbers everywhere.
    – Matthew
    May 24, 2013 at 17:10
  • @Matthew Is there a way to make this work on the entire line ?
    – Hritik
    Aug 23, 2020 at 13:59
  • 2
    @Hritik the accepted answer above should do that: :%s/\d\+/\=(submatch(0)+1)/g. If you only want a single line, remove the % or if you want a specific range of lines, change it to the range you want. For example, for lines 5-10 it would be :5,10s/\d\+/\=(submatch(0)+1)/g.
    – Matthew
    Aug 24, 2020 at 16:47
1

I mis-interpreted the question as to be asking how to increments a number by one on each line, i.e.

var1
var1
var1

to be

var1
var2
var3

So I thought I'd post an answer for that. The link @user606723 provided shows that you can do that with (say between lines 1 and 3):

:let counter=0|1,3g//let counter=counter+1|s/^/\=counter."\t"

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

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