Vim Tips Wiki
(Change to TipImported template + severe manual clean)
(Move categories to tip template)
Line 9: Line 9:
 
|version=6.0
 
|version=6.0
 
|rating=13/7
 
|rating=13/7
  +
|category1=
  +
|category2=
 
}}
 
}}
 
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:
 
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:

Revision as of 09:03, 25 April 2008

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