Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim substitute a Regex with randomly generated numbers

Tags:

vim

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>
like image 523
krjampani Avatar asked Oct 04 '12 19:10

krjampani


2 Answers

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
like image 125
Barton Chittenden Avatar answered Sep 20 '22 15:09

Barton Chittenden


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_
like image 24
Zsolt Botykai Avatar answered Sep 24 '22 15:09

Zsolt Botykai