Vim Tips Wiki
Register
Advertisement
Tip 1114 Printable Monobook Previous Next

created January 25, 2006 · complexity intermediate · author Gerald Lai · version 6.0


This allows a search, and step-by-step confirm & replace, while having the replace string incremented each time if it contains a number at the end of the string. To search for occurrences of "abc", to replace with "xyz0" for the first "abc", "xyz1" for the second "abc", etc, simply do:

:SReplace abc xyz0 1

At any step, you can change from "xyzN" to "defN", and pick up where you left off with the same increment.

Usage: SReplace <search> <substitute> <increment>
command -nargs=+ SReplace call StepReplace(<f-args>)
"makes use of register y
function StepReplace(...)
  if a:0 == 1
    let @y = input("Replace with: ", @y)
    let y = @y
    if @y =~ "\\d\\+$"
      let n = substitute(@y, ".\\{-}\\(\\d\\+\\)$", "\\1", "") + a:1
      let @y = substitute(@y, "\\(.\\{-}\\)\\d\\+$", "\\1".n, "")
    endif
    return y
  elseif a:0 == 3
    let @y = a:2
    execute "%s/".a:1."/\\=StepReplace(".a:3.")/".(&gdefault ? "" : "g")."c"
  else
    echo "Usage: SReplace <search> <substitute> <increment>"
  endif
endfunction

Comments[]

Advertisement