Perl reverse - Reverse file contents with Perl

Working on a Unix system, I just needed to reverse the contents of a file, and thought I'd show how I ended up doing it.

My file-reversal needs

For my situation I needed to (a) get 10 lines from the end of a file, (b) reverse those ten lines, and (c) save them to another file. If my Unix system supported the -r option of the tail command this would have been a no-brainer, but it didn't, so I had to work a little harder.

I ended up using this sequence of commands (including the Perl reverse function call) to solve my file line-reversal problem:

tail my_data_file | perl -e 'print reverse <>' > my_output_file

That sequence of commands can be read as "get the last ten lines from the file named my_data_file, then reverse those lines, and write them to my_output_file."

Working with a file instead of a pipe

If you actually need to work with a file directly (instead of the command pipeline I just showed) you can take the following approach.

Assume that you have a file named foo that has the contents shown below when you cat the file out:

prompt> cat foo
5
1
m
a
z
2

To reverse the file contents just use the Perl reverse command I showed earlier, but this time specify the filename foo:

prompt> perl -e 'print reverse <>' foo 
2
z
a
m
1
5

As you can see it reverses the file contents. To be clear, this is not a sort of the file contents, I'm just reversing the lines from the original file.

Other options

As I mentioned, if your tail command supports the -r option that's probably the most obvious route, but mine did not. From what I've read there is also a tac utility available (the reverse of cat) which does the same thing. I read that this can also be done with sed, but I prefer this perl solution.