2

I have a very large text file that I have opened it in VIM and I need to add 1 to numbers matching some criteria. for example:

Comment 1
Comment 2

[p2,0,0,115]Live! ConcertGrand  
[p2,2,104,5]Live! PopGrand  
[p2,3,104,4]Live! RockPiano 
[p2,4,104,3]Live! AmbientPiano
End of file.

and I'd like to transform this (by adding say 1 to the second element of the list) to

Comment 1
Comment 2

[p2,1,0,115]Live! ConcertGrand  
[p2,3,104,5]Live! PopGrand  
[p2,4,104,4]Live! RockPiano 
[p2,5,104,3]Live! AmbientPiano
End of file.

How can I do this in vim, please?

I have tried:

%s/\[p\zs\d\+\(,\d\+\)\=/\=(1+str2nr(submatch(1)))/

But it does not work. Any help would be greatly appreciated. CS

chikitin
  • 762
  • 6
  • 28
  • 2
    You almost had it right. I just added the `\v` for very magic, changed the separator to `#` and changed your starting point (`\zs`) resulting in `%s#\v\[p\d+,\zs(\d+)#\=(1+str2nr(submatch(1)))` – Lieven Keersmaekers May 19 '17 at 05:20
  • Possible duplicate of [Is it possible to increment numbers using regex substitution?](http://stackoverflow.com/questions/12941362/is-it-possible-to-increment-numbers-using-regex-substitution) – Stephane Janicaud May 19 '17 at 05:34
  • @stej4n - that duplicate is about just using regex doing the substitution which is a whole lot more convulated then using `vim`. A good learning experience but it's of no use to OP. – Lieven Keersmaekers May 19 '17 at 05:46
  • 1
    if you have `perldo`, you can use `:%perldo s/^\[p\d+,\K\d+/$&+1/e` – Sundeep May 19 '17 at 06:25
  • Thank you very much, Lieven. That did it. – chikitin May 19 '17 at 11:33

1 Answers1

3

Do you really need to do this with search and replace? Because there is builtin functionality for addition and subtraction.

:h CTRL-A

CTRL-A: Add [count] to the number or alphabetic character at or after the cursor.

{Visual}CTRL-A: Add [count] to the number or alphabetic character in the highlighted text. {not in Vi}

So you basically could use VISUAL-BLOCK selection on your column of numbers and press CTRL-A and it will add 1 to all of them

If it is more complicated you could use macro

Sardorbek Imomaliev
  • 14,861
  • 2
  • 51
  • 63
  • Upvoted but the visual block selection will not work if the numbers are not aligned which they probably will not be as OP is talking about a large file. A macro would work but that's an order of magnitude slower to execute then a search and replace. – Lieven Keersmaekers May 19 '17 at 06:09
  • @LievenKeersmaekers I was judging by example that he provided, and assumed that in his case they are aligned, but yes, it won't be as good if they are not. – Sardorbek Imomaliev May 19 '17 at 06:11