Wednesday, June 6, 2012

5 ways to reverse the order of file content



 In this article, we will see the different methods in which we can print the file content in reverse order.

Let us consider a file with the following contents:
$ cat file
Linux
Solaris
AIX
1. tac command is the reverse of cat. It simply prints the file in reverse order.
$ tac file
AIX
Solaris
Linux
   Note: tac is not available in all Unix flavors.

2. This option uses a combination of commands to reverse the file order.
$ nl file | sort -nr | cut -f 2-
AIX
Solaris
Linux
 nl commands numbers the file contents. sort sorts the numbered file in the reverse order, and the cut command removes the number and prints the file contents.

3. sed is the most trickiest of all.
$ sed -n '1{h;T;};G;h;$p;' file
AIX
Solaris
Linux
      Many commands of sed are used here. For now, we will discuss it briefly. sed uses 2 things: pattern space & hold space. Pattern space is where a line from the input file is read into. Hold space can be used to temporarily hold data.  The logic is simple: Every time a line is read into the pattern space, concatenate the hold space to the pattern space, and keep it back in the hold space. Once the last line is processed, print the contents in the hold space.
      h : Copy pattern space contents to hold space.
      G: Append hold space content to pattern space.
      T: To skip the remaining part.

   When the first line(1) is read, it is just copied to hold space(h). From the next line, the hold space content is appended(G) to the current pattern space, and the content in pattern space is now moved to hold space. When the last line($) is encountered, the contents in the pattern space are simply printed.

4. awk solution is a pretty simple one.
$  awk '{a[i++]=$0}END{for(j=i-1;j>=0;j--)print a[j];}' file
AIX
Solaris
Linux
 One by one line is read and stored in an array. At the end, the array is printed in the reverse order by starting from the last index.

5. perl solution is pretty simple due to the reverse function of perl.
$ perl -ne 'push @arr,$_;}{print reverse @arr;' file
AIX
Solaris
Linux
  As the file is read, the lines are pushed into an array. Once the file is processed, the array is printed in the reverse order using the reverse function.

  The other option using perl, without using the reverse function:
$ perl -ne 'push @arr,$_;}{while(@arr){ print pop @arr;}' file
AIX
Solaris
Linux
   In this, we keep popping the array element till the array has some element in it. By pushing and popping, it becomes like a stack,LIFO, due to which the file gets printed in the reverse order automatically.
Related Posts Plugin for WordPress, Blogger...

1 comment: