Shuffle lines in Vim
In a pinch, I needed to randomize the order of a few thousand lines of plain text. In Linux you can just pipe the file through sort, even right inside Vim:
:%!sort -R
But I was stuck on Windows. And I don't know how to randomize a file in native Vim script. But doing it in Ruby is pretty easy, and luckily, Vim has awesome Ruby support. Tne minutes' work and a few peeks at :h ruby and we have a successful, working kludge:
function! ShuffleLines()
ruby << EOF
buf = VIM::Buffer.current
firstnum = VIM::evaluate('a:firstline')
lastnum = VIM::evaluate('a:lastline')
lines = []
firstnum.upto(lastnum) do |lnum|
lines << buf[lnum]
end
lines.shuffle!
firstnum.upto(lastnum) do |lnum|
buf[lnum] = lines[lnum-firstnum]
end
EOF
endfunction
2011-07-07 23:32 - Edited to remove a superfluous line.
2011-07-09 21:33 - Wrong parameter for sort, oops.

5 Comments
What is this 'vim' of which you speak?
I saw something similar in IRC, not as fancy, but depending only on vimscript; I documented it here:
http://devnull.li/~jerojasro/blog/posts/randomize_lines_in_a_file/
Small typo: sort -R randomizes, sort -r just reverses the sort order.
Thanks SwifT.
I think that you can replace 8 lines of your code with that onliner:
buf[ firstnum..lastnum ] = buf[ firstnum..lastnum ].shuffle
Speak your Mind
Preview