Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

For example, if I have four lines as follows:

the first line
the second line
the third line
the fourth line

I want to reverse them to

the fourth line
the third line
the second line
the first line

How could I do this in vim?

share|improve this question
Duplicate on Stack Overflow: How to flip a visual selection in vim? – Palec Dec 27 '14 at 14:51
Related: Reverse all lines @ Vim Wikia – Palec Dec 27 '14 at 14:53
up vote 52 down vote accepted

To reverse all the lines in a file,


For an explanation see

:help 12.4

which also shows how to reverse just a range of lines.

share|improve this answer
Great tip on the exact help section! To summarize: 1. set a marker at the last line you want reverse (I name the marker 'a' using ma), 2. move cursor to the first line of the block, 3. type :'a,.g/^/m 'a – Rubistro Dec 6 '13 at 19:25
Yeah, including the actual answer here on the Stack Exchange sites is a must; referring to an external source is not enough. (Citing it, though, props.) – ELLIOTTCABLE Dec 8 '15 at 23:19

Select the desired lines, hit !, and in the resulting prompt pipe the lines through tac a la :'<,'>!tac. See man tac for more details.

share|improve this answer
To select the lines, use shift+v to enter visual line mode, then j to add lines to the selection. – wisbucky May 21 '14 at 21:46

On Mac OS X, tac does not exist, but you can use tail -r to the same effect:

:%!tail -r

This also works nicely for visual mode:

:'<,'>!tail -r

Excerpt from tail(1)'s manpage:

The -r option causes the input to be displayed in reverse order, by line. Additionally, this option changes the meaning of the -b, -c and -n options. When the -r option is specified, these options specify the number of bytes, lines or 512-byte blocks to display, instead of the bytes, lines or blocks from the beginning or end of the input from which to begin the display. The default for the -r option is to display all of the input.

share|improve this answer
Excellent! So to provide 'tac' under OS X: alias tac='tail -r' – Rubistro Dec 6 '13 at 19:27
You can also brew install coreutils and use gtac. – Andrew Marshall Apr 11 '14 at 3:25
" Reverse the lines of the whole file or a visually highlighted block.
    " :Rev is a shorter prefix you can use.
    " Adapted from
command! -nargs=0 -bar -range=% Reverse
    \       let save_mark_t = getpos("'t")
    \<bar>      <line2>kt
    \<bar>      exe "<line1>,<line2>g/^/m't"
    \<bar>  call setpos("'t", save_mark_t)

(Based on: )

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.