tac

Print a file in reverse — last line first. Handy for logs and “latest entries first” views.

Category: Text Processing Reverse lines Logs Pipelines coreutils

What it does

tac outputs a file with lines reversed: the last line becomes the first. It’s effectively cat spelled backwards — and it does the opposite direction of output.

Use it when you want to start reading from the newest lines (common with logs) without needing a pager that jumps to the end.

How it works (mechanical)

tac reads the input and emits records in reverse order. By default, records are separated by newline characters. It may seek backwards from the end of the file (fast on regular files), but on pipes/streams it must buffer (because there’s no “end” to seek from).

  • Regular file: can reverse efficiently by seeking from the end.
  • Pipe/stdin: must buffer input to reverse it later.
  • Separators: supports custom record separators with -s.

10 Practical Examples

# 1) Reverse a file by lines
tac file.txt
# 2) Show the newest 50 lines first (reverse then head)
tac /var/log/syslog | head -n 50
# 3) Read a log from newest to oldest with a pager
tac /var/log/auth.log | less
# 4) Reverse and then search “backwards” (newest matches first)
tac /var/log/syslog | grep -m 10 -i error
# 5) Reverse a file and keep line numbers (nl after tac)
tac file.txt | nl -ba
# 6) Reverse a list of mount users (handy in audits)
tac /var/tmp/inFSTAB
# 7) Reverse records separated by a custom delimiter (example: blank line)
# -s sets the record separator (here: empty line)
tac -s '' notes.txt
# 8) Reverse a file and compare the “tail-first” view to tail -n
tac file.txt | head -n 20
tail -n 20 file.txt
# 9) Reverse + dedupe keeping the last occurrence (newest wins)
tac file.txt | awk '!seen[$0]++' | tac
# 10) Reverse a command output (note: buffers everything)
some_command | tac

Notes & Gotchas

  • Not the same as reversing characters: tac reverses lines/records, not the text in each line.
  • Pipes buffer: on stdin/pipe, tac must read everything before output. For huge streams, this can be slow or memory-heavy.
  • Binary or very large files: use with care; less +G or tail may be better for simple “latest lines”.
  • Better tool sometimes: if you just want the last N lines, use tail -n N.
# Often faster than tac for “just show last 50 lines”
tail -n 50 /var/log/syslog

Historical Context

tac appeared as a playful counterpart to cat (name reversed, behavior reversed). It became practical for log reading and quick inspection workflows where “start from the newest” is the natural human preference.

Related Commands

  • cat — output files normally
  • tail — show last lines (often faster for small N)
  • less — interactive viewing, jump to end with G
  • nl — line numbering (combine with tac)
  • sed, awk — programmable transforms