Putorius
Basic Commands

tac Command - Cat a File in Reverse Order

An image showing a Linux terminal with the command overlay tac command

In this article we will discuss the Linux tac command, which is basically the opposite of the cat command. As we learned in an earlier article, the cat command is basically used for printing file contents to the standard output starting with the first line. The tac command does the the reverse and prints the file contents starting with the last line and working up to the first line.

The options to each command are different but, tac has a couple of options that can be used in some interesting ways.

Basic Usage

The tac command will print out a file contents in reverse, showing the last line first and working it's way up to the first line.

$ tac testfile 
Then a third line
Here is a second line
This is the first line

Below is an image showing the different output of cat vs tac.

The Tac command will also take input form STDIN (Standard input) and reverse it.
NOTE: You must use CTRL+D to exit.

$ tac
one line
two lines
three lines

three lines
two lines
one line

You can also use redirection, which we covered in the cat tutorial already.

Using the Custom Separator

The tac command has different options that cat. For example there are not -n, -e, or -T options in tac. But there is one trick it has that cat does not. That is the custom separator which is useful and fun although I am struggling to fine a practical use for it.

As an example, let's use a comma separated file, like this:

$ cat testfile2
Steve,Joe,Bob,Cindy,Harry,Stacy,

Normally, tac reads files from last LINE to the first. Not last item on the line. That is because the default separator is a new line. We can change the default separator to be any STRING, or even a regex. Let's change the separator to a comma so we can get a reverse list of the names in the file.

$ tac testfile2 -s ,
Stacy,Harry,Cindy,Bob,Joe,Steve,

You can use a regular expression for the customer separator as well. In this example we will tell tax to use any digital. Let's say we had a list of animals and a number representing how many of each we had.

$ cat testfile3
dog1 cats2 birds3 lizards4

We can use tax and a regular expression to use the digit as a separator.

$ tac testfile3 -r -s [0-9]
lizards4 birds3 cats2 dog1

Conclusion

The Linux tac command is a fun and rarely used command. It is basically the opposite of the cat command as it prints output from last line to first. The customer separator option is a fun little tool, but I have yet to find a practical use for it.

I would love to hear any use cases you have come across, please leave them in the comments below.

Exit mobile version