是否可以为vim编写脚本,以便查找字符串,例如gkfjjcjfk8483jdjd7。然后用另一个随机生成的字符串替换找到的字符串?它必须能够生成随机数字和其他字符串。
如果有人能用这样的剧本帮助我,我会非常感激。
答案 0 :(得分:2)
你走了:
function! ReplaceWithRandom(search)
" List containing the characters to use in the random string:
let characters = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',]
" Generate the random string
let replaceString = ""
for i in range(1, len(a:search))
let index = GetRandomInteger() % len(characters)
let replaceString = replaceString . characters[index]
endfor
" Do the substitution
execute ":%s/" . a:search . "/" . replaceString . "/g"
endfunction
function! GetRandomInteger()
if has('win32')
return system("echo %RANDOM%")
else
return system("echo $RANDOM")
endif
endfunction
可以像这样调用该函数::call ReplaceWithRandom("stringtoreplace")
。并且它将替换由characters
中列出的字符组成的随机字符串作为参数传递的字符串的所有出现。
请注意,我包含了一个辅助函数,它可以从系统中获取随机数,因为Vim没有提供随机生成器。
作为奖励,您可以将其作为紧急呼叫的命令:
command! -nargs=1 RWR call ReplaceWithRandom(<f-args>)
然后您可以执行::RWR "stringtoreplace"
编辑:如果您希望随机字符串在搜索到的字符串的每个出现时都不同,您可以用以下字符替换该函数:
function! ReplaceWithRandom(search)
" List containing the characters to use in the random string:
let characters = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',]
" Save the position and go to the top of the file
let cursor_save = getpos('.')
normal gg
" Replace each occurence with a different string
while search(a:search, "Wc") != 0
" Generate the random string
let replaceString = ""
for i in range(1, len(a:search))
let index = GetRandomInteger() % len(characters)
let replaceString = replaceString . characters[index]
endfor
" Replace
execute ":s/" . a:search . "/" . replaceString
endwhile
"Go back to the initial position
call setpos('.', cursor_save)
endfunction