我需要这个解决方案,但也需要支持前导零。我的使用方式更像示例1,而不是示例2(这是原始示例)。
我创建了一个名为SearchIncr()(搜索、替换和递增)
的函数。
有四个必需参数:target_string
、replacement_string
、start_value
、increment_value
。
还有两个可选参数:leading_zeros
、position
leading_zeros
是正整数值,position
是“before”或“after”。参见示例2。
示例1
:'<,'>call SearchIncr("0 0","new",1,5,8)
如果文件看起来像这样:
what 0 0 post
areu 0 0 post
doin 0 0 post
然后您将得到:
what new00000001 post
areu new00000006 post
doin new00000011 post
示例 2
:'<,'>call SearchIncr("0;","px;",-18,-18,0,'after')
如果文件长这样:
.star_10 {
background: url(stars.png) no-repeat 0 0;
}
.star_10 {
background: url(stars.png) no-repeat 0 0;
}
.star_10 {
background: url(stars.png) no-repeat 0 0;
}
你将会得到以下内容:
.star_10 {
background: url(stars.png) no-repeat 0 -18px;
}
.star_10 {
background: url(stars.png) no-repeat 0 -36px;
}
.star_10 {
background: url(stars.png) no-repeat 0 -54px;
}
vimscript在这里:
" place functions here
function! SearchIncr(a1,a2,a3,a4,...)
" patn, repl, start, increment
let target = a:a1
let repl = a:a2
let startval = a:a3
let increment = a:a4
" 1st optional argument handles leading zeros
" process optional leading zero
if a:0 >= 1
let leadingz = a:1
else
" default to 0
let leadingz = 0
endif
" 2nd optional argument handles if target string goes before or after
" default is before
if a:0 == 2
" ideally set to 'after'
let repl_pos = a:2
else
let repl_pos = 'before'
endif
" inits
let l:incr = startval - increment
let lnum = a:firstline
" cycle though selection
while lnum <= a:lastline
" the FORMATTING string
if repl_pos == 'before'
let l:incrstring = '\=printf(''%s%0'. leadingz . 'd'',repl,l:incr)'
elseif repl_pos == 'after'
let l:incrstring = '\=printf(''%0'. leadingz . 'd%s'',l:incr,repl)'
else
"default to no leading zero and before placement
let l:incrstring = '\=printf(''%s%0d'',repl,l:incr)'
endif
" only increment counter when target matches
if match(getline(lnum),target) > 0
let l:incr = l:incr + increment
endif
" the search and replace
call setline(lnum,substitute(getline(lnum),target,
\ l:incrstring,'g'))
let lnum = lnum + 1
endwhile
endfunction
如果有任何意见可以改进上面的内容,将不胜感激!