Brendan Dawes
The Art of Form and Code

Reversing Selected Lines in Vim

This was something I needed to do recently, having listed some events on my site but then later realising they were in the reverse order of a list elsewhere on the same page.

Rather than type them all in again, I used the power of Unix inside Vim to quickly reverse the lines.

With my cursor on the first line that I wanted to reverse I went into Visual Selection Line mode by pressing V. I then used the j key to select the rest of the lines I needed to reverse. Then I pressed : to go into the command mode and typed:

!tail -r

The exclamation mark tells Vim we want to use a Unix command. We then use tail but add the -r flag to reverse it. The selected lines are now reversed. Wonderful.

reversing the lines in vim

By default the tail command outputs the last ten lines of a file (or in this case a selection). If you want more lines you can use the -n flag to define how many lines you need.

There is also another way, handy for when you want to reverse the whole document, without using a Unix command:

:g/^/m0

This works through every line of the document, goes to the beginning of the line and then moves that line to line 0 of the document, repeating this for every line.