When I enter visual mode, :'<,'>sort allows me to sort alphabetically the lines I have selected, obviously starting from the left most characters on a line going to the right.

Is it possible to reverse this, so I sort alphabetically with the right most characters to the left?

1 Answer 1


If you can use the rev command, you could reverse each line, sort and reverse again, using external commands in a pipe:

%!rev | sort | rev

This can be done entirely in Vimscript, but it's way more verbose:

function! RTLSort() range
    " reversing function for use with map()
    function! Rev(k, str)
        " the first argument from map() is an index, so it's ignored.
        return join(reverse(split(a:str, '\zs')), '')
    let l:Rev = function("Rev")
    let l:lines = getline(a:firstline, a:lastline)
    call setline(a:firstline, map(sort(map(l:lines, l:Rev)), l:Rev))

Then, something like:

:%call RTLSort()
:3,9 call RTLSort()

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.