Print File Contents in Reverse Order (“reverse cat”)
The ‘cat’ utility serves it’s purpose print the content of a file at once. So do ‘more’ and other tools as well. But they all do in ‘forward’ mode only.
To print a file in reverse order, at least some linux distros come with the ‘tac’ command, which will do a ‘reverse cat’.
But what to do, if ‘tac’ is missing?
If you don’t want to go for an additional tool to compile and install, why not check out Perls abilities?
Here’s how to do it with a PIPE:
[gianpaolo@localhost ~]$ cat filename | perl -e 'print reverse <>;'
You can also run it directly on a filename like this:
[gianpaolo@localhost ~]$ perl -e 'print reverse <>;' -f filename
You can do it with ‘sed’ as well:
[gianpaolo@localhost ~]$ cat filename | sed -n '1!G;h;$p'
[gianpaolo@localhost ~]$ sed -n '1!G;h;$p' filename
Personally I favor the Perl method as it’s easier to memorize, despite having more to type 😉
Enjoy!