How to use tac command in Linux?

The cat is one of the most frequently used commands in Linux which is used to print the content of a file on the standard output. This command is also used to create, append the content of one file to the end of another file, and view the content of a file.

The tac command is the reverse of the cat command in Linux. It is rarely used to concatenate and print files in reverse. It prints the last line first and the first line in the last.

In this article, I will discuss the usage of the tac command along with some examples.

The syntax of the tac command

The syntax of how to use the tac command in Linux is given below.

 tac [OPTION]... [FILE]...

Where you can use the given options with tac command.

-b, --before – This option will attach the separator before instead of after
-r, --regex – This will interpret the separator as a regular expression
-s, --separator=STRING – This makes tac command use STRING as the separator instead of the newline
--help – The option is used to display the help page
--version – Display the version information of tac and exit

Examples of using tac command in Linux

The following examples show the usage of the tac command in Linux.

Let’s say we have a file named countries.txt which contains names of some countries.

Using the cat command you can see the original content of this file is displayed in the given image.

cat countries.txt

Using tac command without any options

If you print the content of the given file using the tac command it will get printed in reverse order.

tac countries.txt

You can see the output of this command in the given image.

How to make tac use a custom separator

To make tac use a custom separator( instead of a newline) you need to use the option -s this will separate the content of a file based on a string or a keyword from the file.

For example –

echo "INDIA,RUSSIA" | tac

This will produce the given output.

Now when you use a comma as a separator then the output of the above command will look like as it is given in the image below.

echo "INDIA,RUSSIA" | tac -s

Using option -b with tac command

If you want to attach the separator before instead of after then use the option -b with tac command.

For example –

echo "INDIA,RUSSIA" | tac -b -s ,

From the output of this command, you can see the difference in using separator after and before.

For more information, you can see the man page of the tac command.

man tac

Conclusion

I hope you understand the use of the tac command in Linux. Now if you have a query then leave it in the comment below.

Leave a Comment