tac – reverse the lines of a file
May 6th, 2009Before you write a script like this look for someone else who has already done 99% of the work. The tac command will reverse the lines of a file and is therefore extremely useful in various situations.
The tac man page has further details.
Basically, tac will cat a file backwards. However, many operating systems do not include the tac command by default and for some operating systems tac is not yet available.
On many systems you may use tail. I believe the version of tail on Solaris may have a different flag.
cat myfiile | tail -r
By default the -r flag will cause tail to print the entire file rather than just the tail portion of the file.
Be very wary of the rev command availible on most BSD based systems. The has further details. However, this command will reverse the chracters rather than the lines of a file.
The following command sequence should actually reverse the lines on most systems :
cat -n myfile | sort -nr | cut -c 8-
However, please keep in mind that if you have a very long file then this may not work correctly. In which case using a script say in ruby or a version of tac for your system may be the best approach.
The following command sequence should actually reverse the lines on most systems :
cat -n myfile | sort -nr | cut -c -f2-
You can also use sed to reverse the file :
cat myfile | sed ‘x;1!H;$!d;x’
Probably the most memorable of these is the following Perl comamnd
cat myfile | perl -e ‘print reverse <>‘
Perl is available for many systems as is ruby. Perhaps the script in ruby to reverse the lines is not actually all that silly.
If you are running Windows and you really do not want to install perl or tac then check out this I found this article which may work?