bashvim

Sorting words (not lines) in VIM


The built-in VIM :sort command sorts lines of text. I want to sort words in a single line, e.g. transform the line

b a d c e f

to

a b c d e f

Currently I accomplish this by selecting the line and then using :!tr ' ' '\n' | sort | tr '\n' ' ', but I'm sure there's a better, simpler, quicker way. Is there?

Note that I use bash so if there's a shorter and more elegant bash command for doing this it's also fine.

EDIT: My use-case is that I have a line that says SOME_VARIABLE="one two three four etc" and I want the words in that variable to be sorted, i.e. I want to have SOME_VARIABLE="etc four one three two".

The end result should preferably be mappable to a shortcut key as this is something I find myself needing quite often.


Solution

  • Using great ideas from your answers, especially Al's answer, I eventually came up with the following:

    :vnoremap <F2> d:execute 'normal i' . join(sort(split(getreg('"'))), ' ')<CR>
    

    This maps the F2 button in visual mode to delete the selected text, split, sort and join it and then re-insert it. When the selection spans multiple lines this will sort the words in all of them and output one sorted line, which I can quickly fix using gqq.

    I'll be glad to hear suggestions on how this can be further improved.

    Many thanks, I've learned a lot :)

    EDIT: Changed '<C-R>"' to getreg('"') to handle text with the char ' in it.