Linux tac Command Tutorial for Beginners (with Examples)

We’ve already discussed the Linux cat command in one of our earlier tutorials. As you may be aware, the cat command is mainly used for displaying file contents in output. However, what you may not be aware of is that there exists a command that does exactly opposite of what cat does.

The tool in question is tac, and in this tutorial, we will discuss its basics using some easy to understand examples. But before we do that, it’s worth mentioning that all examples in this article have been tested on an Ubuntu 16.04 LTS machine.

Linux tac command

Tac is opposite to cat in the sense that the output it produces is presented in a way that the last line is displayed first, then the second last line, and so on. Following is the tool’s syntax:

tac [OPTION]… [FILE]…

And here’s what tac’s man page says about it:

Write each FILE to standard output, last line first. With no FILE, or when FILE is -, read 
standard input.

Following are some Q&A-styled examples that should give you a good idea on how the tool works.

Q1. How to use tac?

Simple, just run the ‘tac’ command with a filename as input.

tac [filename]

For example:

tac file2

How to use tac

So you can see the output produced by tac is exactly opposite of what cat produced.

Q2. How to make tac use custom separator (not newline)?

For this, you’ll have to use the -s option. For example, the following command

echo “1,2” | tac

Produced this output:

1,2

That’s because newline is the default separator for tac.

However, the command below:

echo “1,2” | tac -s ,

produces the following output:

2
1,

That’s because now the separator has been changed.

Q3. How to change the position of separator?

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

For example:

echo “1,2” | tac -b -s ,

produces the following output:

,2
1

Q4. How to make tac accept input from STDIN?

In case you want the tac command to accept input from the standard input, just don’t pass any file name to it.

tac

Once you run the command in the way mentioned above, it will wait for you to input content. Once you are done with that, press Ctrl+d to signify you’re done, and then tac will produce its output on STDOUT.

Conclusion

As you can see, tac is easy to understand and work with. The number of command line options it offers is limited, and we’ve discussed most of them here. You can learn more about the command by heading to its man page.

Share this page:

linux tac command tutorial for beginners with examples 1
linux tac command tutorial for beginners with examples 2
linux tac command tutorial for beginners with examples 3
linux tac command tutorial for beginners with examples 4

نوشته های مشابه