sponsor Vim development Vim logo Vim Book Ad

basic Tip #813: Reverse all the lines in a file

 tip karma   Rating 61/29, Viewed by 1873 

Read and edit this tip on the Vim tip wiki. The wiki may have a more recent version of this tip.

created:   October 30, 2004 12:32      complexity:   basic
author:   Mohammad Farooq      as of Vim:   6.0

This simple command

   :g/^/m0

will reverse all the lines in a file. Useful for certain files like logs.

 rate this tip  Life Changing Helpful Unfulfilling 

<< Keep modified [+] flag after writing to a file | Use cygwin shell >>

Additional Notes

zzapper, October 31, 2004 5:32
:g/^/  means match any or all lines (where ^ matches beginning of line, .* or $ would also work).
m0  (move to line zero) Starting from top move each line to the top.

:g/^/m0

repeating the command brings all back to the original order

:g/^/t0    mirrors the contents of the file (t=transfer)
:g/^/t$    duplicates the contents of the file
[email protected], October 31, 2004 20:52
u can use this in linux

:%! tac
[email protected], October 31, 2004 20:57
Tip #29: reverse all the line with only 7 keystroke in vim
[email protected] - NOSPAM, November 2, 2004 10:00
Here are two visual-mode maps: one for reversing line order (\fr) and the
other for mirror-imaging horizontally (\fR):

vmap <Leader>fr   :<c-u>set lz<CR>'>o<Esc>'<O<Esc>V'>j:<c-u>'<+1,'>-1g/^/m '<<CR>'<dd'>dd:set nolz<CR>
vmap <Leader>fR   c<C-O>:set ri<cr><C-R>"<esc>:norm! dd`<<cr>:set nori<cr>
Anonymous, November 2, 2004 10:29
:help 12.4
Anonymous, November 3, 2004 8:12
Perhaps simpler:
vnoremap <Leader>fr <Esc>'<O<Esc>V'>:g/^/m '<<CR>'<dd
vnoremap <Leader>fR c<C-O>:set ri!<CR><C-R>"<Esc>:set ri!<CR>

I try not to assume the values of options.  The first above looks ugly without lazyredraw, but doesn't unset it at the end.
[email protected] - NOSPAM, November 5, 2004 6:02
Options are often problematical; frequently options such as virtualedit, compatible, etc collide with mappings.
However, lazyredraw is one of those options whose purpose, IMHO, is to make mappings and function
calls cleaner, and has little/no purpose otherwise.  As a result, keeping lazyredraw out of maps and function
calls is counterproductive; in my opinion, of course.
Hal Atherton, November 8, 2004 18:28
Easier to remember, and useful with visual mode:

command! -range=% Reverse  <line1>,<line2>g/^/m0
"                 REVERSE line ordering, and  move those lines to the top of the file.

So in the default case,
:Reverse
will reverse order the entire file.

Or manually reverse lines 20 through 30 by,
:20,30Reverse
and find the result at the top of the file.


If you have questions or remarks about this site, visit the vimonline development pages. Please use this site responsibly.
Questions about Vim should go to [email protected] after searching the archive. Help Bram help Uganda.
   
Sponsored by Web Concept Group Inc. SourceForge.net Logo