[How To]: Linux tac Command – Usage and Examples

Linux tac Command


tac command practically is reverse version of cat command. It means, any result in cat command will be reversed by tac command.

tac is lesser known and less used command in Linux but I want to show you the command usage and some examples.

Usage and Examples


tac command has few options same as cat command, we’ll review some of its options at the below.

Example 1

Comparison cat and tac outputs. In this example, we have a file with the below content:

[root@localhost ~]# cat sample1.txt
This is first line.
This is second line.
This is third line.
This is fourth line.

Now, print the file’s content by tac:

[root@localhost ~]# tac sample1.txt 
This is fourth line. 
This is third line. 
This is second line. 
This is first line.

Example 2

Both tac and cat commands has separator option which one of the most important options and the command is represented by the -s switch, which separates the contents of the file based on a string or a keyword from the file.

[root@localhost ~]# cat sample1.txt
---1---
1
2
3
---2
A
B
C
---3--
a
b
c
[root@localhost ~]# tac --before --regex --separator=^---[0-9]+-*$ sample1.txt
---3--
a
b
c
---2
A
B
C
---1---
1
2
3

Example 3

The most important usage of tac command is, that it can provide a great help in order to debug log files, reversing the chronological order of log contents.

[root@localhost ~]# tac /var/log/yum.log
Sep 12 17:29:39 Installed: iptables-services-1.4.21-17.el7.x86_64
Sep 12 16:50:33 Updated: iptables-1.4.21-17.el7.x86_64
Sep 12 16:43:11 Installed: openvpn-2.4.3-1.el7.x86_64
Sep 12 16:43:11 Installed: pkcs11-helper-1.11-3.el7.x86_64
Sep 12 16:39:12 Installed: epel-release-7-9.noarch
Sep 12 16:37:51 Installed: ntp-4.2.6p5-25.el7.centos.2.x86_64
Sep 12 16:37:51 Updated: ntpdate-4.2.6p5-25.el7.centos.2.x86_64

Or display the last lines by tac command.

[root@localhost ~]# tail /var/log/yum.log | tac
Sep 12 17:29:39 Installed: iptables-services-1.4.21-17.el7.x86_64
Sep 12 16:50:33 Updated: iptables-1.4.21-17.el7.x86_64
Sep 12 16:43:11 Installed: openvpn-2.4.3-1.el7.x86_64
Sep 12 16:43:11 Installed: pkcs11-helper-1.11-3.el7.x86_64
Sep 12 16:39:12 Installed: epel-release-7-9.noarch
Sep 12 16:37:51 Installed: ntp-4.2.6p5-25.el7.centos.2.x86_64
Sep 12 16:37:51 Updated: ntpdate-4.2.6p5-25.el7.centos.2.x86_64

Davoud Teimouri

Professional blogger, vExpert 2015/2016/2017/2018/2019/2020/2021/2022/2023, vExpert NSX, vExpert PRO, vExpert Security, vExpert EUC, VCA, MCITP. This blog is started with simple posts and now, it has large following readers.

Leave a Reply

Your email address will not be published. Required fields are marked *