O'Reilly logo

Linux Shell Scripting Cookbook by Sarath Lakshman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Printing lines in the reverse order

This is a simple recipe. It may not seem very useful but it can be used to emulate the stack data structure 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...

Let's do it with tac first. The 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.

Let's do it in awk as follows:

$ seq 9 | \
awk '{ lifo[NR]=$0; lno=NR } 
END{ for(;lno>-1;lno--){ print ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required