Text and processing
The tac command
Prints the lines in reverse order, the last one first. It is cat backwards.
Most useful options
-b, --beforePuts the separator before each record instead of after it.-r, --regexTreats the separator as a regular expression.-s, --separator <cadena>Uses that string as the separator instead of the newline.--helpShows the help and exits.--versionShows the version and exits.Copy-ready examples
$ seq 1 3 | tacreverses a sequence of numbers.Example output
3 2 1
$ printf 'a\nb\nc\n' | tacthe same with lines of text.Example output
c b a
$ echo "a,b,c" | tac -s ','reverses by records separated by commas, not by lines.Example output
c b,a,
$ tac registro.log | head -n 5the five most recent entries of a log, the newest first.You can try them in the browser terminal: it does not touch your computer.
Common errors
| Message | Cause | Fix |
|---|---|---|
| tac: invalid option -- 'Q' | tac has no -Q option. Its options are -b, -r and -s, plus --help and --version. | Fix the option or check tac --help. |
| tac: failed to open 'nofile' for reading: No such file or directory | The file does not exist or the name is mistyped. The quotes around the name depend on the locale settings. | List the folder with ls and copy the exact name. |
Typical mistakes
- It reverses the order of the lines, not the characters inside each one: that is what rev is for.
- If the file does not end in a newline, tac adds none: printf 'a\nb' | tac prints 'ba' on a single line.
- With input that cannot seek, such as a pipe, tac first buffers a copy in $TMPDIR, or in /tmp when that variable is not set.
Differences from similar commands
- cat: shows the file in its normal order. With tac, the same content comes out backwards, line by line.
- rev: reverses the characters inside each line and keeps the order of the lines. tac does the opposite.
sort -r: sorts alphabetically in descending order, so it changes the order based on content. tac only reverses what was already there.
FAQ
What is the difference from tail -n 5?
tail -n 5 shows the last five lines in their original order. tac | head -n 5 shows those same five, with the last one first.
What exactly does the -s option do?
It changes the separator that ends each record; by default it is the newline. The separator stays attached to the record before it: with echo "a,b,c" | tac -s ',' you get c, a newline and then b,a,. With -b it goes in front.
Can I search and read in reverse at the same time?
Yes: grep 'ERROR' app.log | tac shows the matches from newest to oldest, if the log is written in order.
Learn to actually use it
The basic Linux course takes you from zero to console fluency with 24 self-grading lessons.
Start the free course