2016-05-18 10 views
1

vim用のスクリプトを作成して、たとえばgkfjjcjfk8483jdjd7のような文字列を探すことは可能ですか?そして、見つかった文字列をランダムに生成された別の文字列に置き換えますか?ランダムな数字やその他の文字列を生成できる必要があります。文字列を探してランダムな文字と数字に置き換えるスクリプト

誰でもこのようなスクリプトで私を助けることができれば、本当に感謝します。

答えて

2

ここに行く::call ReplaceWithRandom("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',] 

    " 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 

機能は次のように呼び出すことができます。引数として渡された文字列のすべての文字列を、charactersにリストされている文字で構成されるランダムな文字列に置き換えます。

Vimはランダムジェネレータを提供していないため、システムから乱数を得るヘルパ関数を追加しました。あなたはそれコール固定するためのコマンドにすることができボーナスとして

:RWR "stringtoreplace"


編集

command! -nargs=1 RWR call ReplaceWithRandom(<f-args>) 

をそれから行うことができますし、ランダムな文字列にしたい場合は、検索された文字列の出現ごとに異なる場合は、この関数で置き換えることができます。

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