Printing lines in the reverse order

This is a very simple recipe. It may not seem very useful, but it can be used to emulate the stack datastructure in Bash. This is something interesting. Let's print the lines of text in a file in reverse order.

Getting ready

A little hack with awk can do the task. However, there is a direct command, tac , to do the same as well. tac is the reverse of cat.

How to do it...

We will first see how to do this with tac.

  1. The tac syntax is as follows:
    tac file1 file2 …
    

    It can also read from stdin, as follows:

    $ seq 5 | tac
    5 
    4 
    3 
    2 
    1
    

    In tac, \n is the line separator. But, we can also specify our own separator by using the -s "separator" option.

  2. We can do it in awk as follows:
    $ seq 9 | \
    awk '{ lifo[NR]=$0 } 
    END{ for(lno=NR;lno>-1;lno--){ ...

Get Linux Shell Scripting Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.