Search and Replace with incremented values in Vim

前端 未结 5 533
北恋
北恋 2021-01-31 03:57

Lets say I wrote a simple CSS rule like this:

.star_10 {
  background: url(stars.png) no-repeat 0 0;
}

And I need 10, so I copied it 9 times.

5条回答
  •  温柔的废话
    2021-01-31 04:30

    You can use the s/pattern/replace construct with the \= symbol in order to evaluate a function or expression, as shown:

    Decrementing the .star_10:

    let g:decr = 11
    
    fu! Decr() 
      let g:decr = g:decr - 1
      return g:decr
    endfu
    
    :%s/.star_10/\=".star_" . Decr()/
    

    Similarly, you'd do

    let g:decr_18 = 18
    fu! Decr18() 
      let g:decr_18 = g:decr_18 - 18
      return g:decr_18
    endfu
    

    and then replace the 0 0; with a

    :%s/no-repeat 0 0;/\="no-repeat 0 " . Decr18() . "px"/
    

    For both functions, a (global) variable is declared that is manipulated within the functions and returned. The functin itself is called for every line matching the pattern. the pattern is substituted with the expression following the \=.

提交回复
热议问题