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

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

3 Answers

up vote 19 down vote accepted

To reverse all the lines in a file,

:g/^/m0

For an explanation see

:help 12.4

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

share|improve this answer

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
Cannot be any easier. Thanks! – sjas Apr 4 at 6:39
" Reverse the lines of the whole file or a visually highlighted block.
    " :Rev is a shorter prefix you can use.
    " Adapted from http://tech.groups.yahoo.com/group/vim/message/34305
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: http://tech.groups.yahoo.com/group/vim/message/34305 )

share|improve this answer

Your Answer

 
discard

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.