Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to shuffle a list in vim?

What is the best way to shuffle a list in Vim?

I'm trying to randomly sort lines in vim (using vimscript). I created for this a list with all line numbers (in my selection).

p.e. if I select from line 10 to 20 my list will be:

mylist = ['10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20'] 

I would like to sort the lines randomly and with a for loop put them back in the same selection in the new sequence. In order to realize this I would like to shuffle the list many times but don't know how to shuffle the list.

Another solution would be to pick an index from my last randomly.

Can't find out what is the best way.

I know I can sort lines using python, ruby or with other languages but I don't want to install them. I would like to realize above using vimscript.

like image 461
Reman Avatar asked Jul 14 '13 19:07

Reman


People also ask

How do I sort a list in Vim?

Sorting text in Vim is easy! Select the text, then press : , type sort , then hit enter! It'll sort the whole document by default, but you can enter a range too.

How do you shuffle a line in a text file in Linux?

Using the shuf Command The shuf utility is a member of the GNU Coreutils package. It outputs a random permutation of the input lines. The shuf command will load all input data into memory during the shuffling, and it won't work if the input file is larger than the free memory.


2 Answers

You could go "UNIX style" and use the shuf command from the coreutils package:

:10,20!shuf<CR> 
like image 107
romainl Avatar answered Sep 22 '22 23:09

romainl


UPDATE as of 2019:

osx now includes a -R flag in sort, so you should be able to just use

:'<,'>!sort -R

=== Previous answer: ===

Sort does not have a -R flag in osx, so:

brew install coreutils

select lines in vim, and run:

:'<,'>!gsort -R

like image 42
BananaNeil Avatar answered Sep 25 '22 23:09

BananaNeil