I want a file that contain only 1 and 0 for my java networking program. Writing a big file containing only 1 and 0 is boring. So, if vim do this, it is better.

I don't know that it is whether possible or not, but I guess it is possible in vim.

3 Answers 3


To use a purely vimscript solution you can use some functions I described in another answer of mine:

" Randomization Variables
" with a little extra randomized start from localtime()
let g:rndm_m1 = 32007779 + (localtime()%100 - 50)
let g:rndm_m2 = 23717810 + (localtime()/86400)%100
let g:rndm_m3 = 52636370 + (localtime()/3600)%100

function! Rndm()
    let m4= g:rndm_m1 + g:rndm_m2 + g:rndm_m3
    if( g:rndm_m2 < 50000000 )
        let m4= m4 + 1357
    if( m4 >= 100000000 )
        let m4= m4 - 100000000
        if( m4 >= 100000000 )
            let m4= m4 - 100000000
    let g:rndm_m1 = g:rndm_m2
    let g:rndm_m2 = g:rndm_m3
    let g:rndm_m3 = m4
    return g:rndm_m3

Once you added these function to your .vimrc you can also add the following one. It is take the length of the desired string as argument and put the string in your unamed register. This way you can simply paste it whereever you want:

function! Random01(length)
    let s=''
    while len(s) < a:length
        let s .= Rndm()%2

    call setreg('"', s, 'v')

Now you can do :call Random01(30) to generate a string of 30 zeros and ones and simply add it to your buffer with p. On my machine :call Random01(100000) is almost instantaneous.

In this function I put the string in a register but you can of course use it as in the other answers too.


Vim does not have built-in support for randomness. However, if you have Python support, you can use this quick one-liner:

:.pydo n=5; import random; return ''.join([random.choice(['0', '1']) for x in range(n)])

It will replace the current line with n 1s and 0s.

  • Change n=5 to the number of characters you want.
  • Change . to another line range if you want more than one line. Removing the dot will change all lines.

:help :pydo for details.

See @grodzik's answer if you don't have Python support but are on a Unix-like system.


One way to do this is to use system('echo $RANDOM'):

function! MyGenerator(iter)
  let s = ""
  for k in range(a:iter)
    let s .= string(system('echo $RANDOM')%2)
  execute "normal! a".s

command -nargs=1 Generate01 :call MyGenerator(<args>)

With this in your .vimrc all you need to do is:

:Generate01 1000

(or whatever value you want instead of 1000)

It's quite time consuming for large values, though - but still much faster than typing by hand ;)

  • This relies on the user's shell being one that supports $RANDOM as a way to get a random value.
    – jamessan
    Commented Apr 28, 2017 at 15:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.