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.
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
.
We will first see how to do this with tac
.
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.We can do it in
awk
as 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.