Is it possible to substitute a regular expression with a randomly generated number in Vim ? The (random) number to be replaced should be different for each pattern that matches the regular expression. Here's an example of what I need.
Input File:
<a>XYZ</a>
<a>XYZ</a>
<a>XYZ</a>
<a>XYZ</a>
After substituting XYZ with random numbers, the output could be:
<a>599</a>
<a>14253</a>
<a>1718</a>
<a>3064</a>
If you don't mind a little perl in your vim, you can use
:%! perl -pne 's/XYZ/int(rand 1000)/ge'
Edit: updated to allow unlimited substitutions on a given line, per suggestion by @hobbes3, so
XYZ XYZ
XYZ XYZ XYZ
XYZ XYZ XYZ XYZ XYZ XYZ
XYZ XYZ
Becomes something like
86 988
677 477 394
199 821 193 649 502 471
732 208
Try this: put the below code to a buffer then source it (:source %
).
let rnd = localtime() % 0x10000
function! Random()
let g:rnd = (g:rnd * 31421 + 6927) % 0x10000
return g:rnd
endfun
function! Choose(n) " 0 n within
return (Random() * a:n) / 0x10000
endfun
Then you can do:
:s_\(<a>\).*\(</a>\)_\1\=Choose(line('.')*100).\2_
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With