4 different ways to print file content reversely

Let's have some fun with the command line. In this article, I will list 4 different ways that I know with which we can print the file content in a reverse order.

Let's say we have a sample file like this:
 1  
 2  
 3  
 4  


Here are the 4 methods we can use to print the file reversely:

1. Use tac

This is the simplest way. The tac command is the reverse of "cat", so it just prints the file content in reverse order:


2. Use sort

The sort command write sorted concatenation of the file to output. And with the "-nr" option, we will have a reversed output of the file content:



3. Use awk

We can use a complex command with awk here. First we read the lines one by one, then we store them in an array. After that, print the array from the last line. The final command will be:
 awk '{a[i++]=$0}END{for(j=i-1;j>=0;j--)print a[j];}' file  


 4. Use perl

Perl has the "reverse" function which can be used to do the task. First we read the file then push the content into an array. After that, we use the reverse function to print the content in reverse order. The final command will be:
 perl -ne 'push @arr,$_;}{print reverse @arr;' file  


linux tips and tricks