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.
The
tacsyntax is as follows:tac file1 file2 …It can also read from
stdin, as follows:$ seq 5 | tac 5 4 3 2 1
In
tac,\nis the line separator. But, we can also specify our own separator by using the-s"separator" option.We can do it in
awkas follows:$ seq 9 | \ awk '{ lifo[NR]=$0 } END{ for(lno=NR;lno>-1;lno--){ print lifo[lno]; } }'
\in the shell script is used to conveniently break a single line command sequence into multiple lines.
How it works...
The awk script is very simple. We store each of the lines into an associative array...