← Linux and the Command Line
Lesson 13 of 51 · 10 XP
tac — lines in reverse order
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
tac is cat the other way round: it prints a file's lines from the last to the first.
tac log.txt # the most recent log entries on top
Our mini Linux (BusyBox) has no tac command. That's a good reason to learn to do the same thing with standard tools, because servers sometimes have a minimal set of programs too.
A version with awk: remember all the lines in an array, and at the end print them from the end.
awk '{ line[NR] = $0 } END { for (i = NR; i > 0; i--) print line[i] }' file.txt
NRis the number of the current line;$0is the whole line;- the
END { … }block runs after the last line.
We'll look at awk in detail in a couple of lessons. There's also a classic trick with sed: sed '1!G;h;$!d'. It works everywhere, but it reads like a spell.
Task. Without using tac, print the lines of the input in reverse order.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.