Printing lines in the reverse order
This recipe may not seem useful, but it can be used to emulate the stack data structure in Bash.
Getting ready
The simplest way to accomplish this is with the tac command (the reverse of cat). The task can also be done with awk.
How to do it...
We will first see how to do this with tac.
- The syntax of
tacis as follows:
tac file1 file2 ... The tac command can also read from stdin:
$ seq 5 | tac 5 4 3 2 1
The default line separator for tac is \n. The -s option will redefine this:
$ echo "1,2" | tac -s , 2 1
- This
awkscript will print lines in the reverse order:
seq 9 | \
awk '{ lifo[NR]=$0 } \
END { for(lno=NR;lno>-1;lno--) { print lifo[lno]; }
}'\ in the shell script is used to break a single-line command sequence into multiple lines.
How it works...
The awk script stores each of the lines into an associative array using the line number as the index (NR returns...