Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I renumber a list in vim?

Tags:

regex

vim

math

I wrote a section of a webpage that had the following bit...

<span id="item01">   some first presented text</span>
<span id="item02">   some other text, presented second</span>
<span id="item03">   more text</span>
....
<span id="item15">  last bit of text.</span>

I then realized that it should have been numbered from 14 to 0, not 1 to 15. (Yes, bad design on my part, not planning out the JavaScript first.)

Question. Is there an easy way in vim to do math on the numbers in a regular expression? What I would like to do is a search on the text "item[00-99]", and have it return the text "item(15-original number)"

The search seems easy enough -- /item([0-9][0-9])/ (parentheses to put the found numbers into a buffer), but is it even possible to do math on this?
Macro for making numbered lists in vim? gives a way to number something from scratch, but I'm looking for a renumbering method.

like image 735
Jest Phulin Avatar asked Sep 25 '15 07:09

Jest Phulin


1 Answers

:%s/item\zs\d\+/\=15 - submatch(0)/

will do what you want.
Breaking it down:

  • item\zs\d\+: match numbers after item (the \zs indicates the beginning of the match)
  • \=: indicate that the replace is an expression
  • 15 - submatch(0): returns 15 minus the number matched
like image 90
Marth Avatar answered Sep 22 '22 06:09

Marth