Recently encountered a challenge to display the standard output (stdout) of a Linux command in the reverse order.
For eg; ls -lrt would list the files and directories based on the created/updated date but would like to get the output in the reverse direction.
Solution: Linux shell is abundant of features. It has a built-in command namely tac
part of the coreutils written by Jay Lepreau and David MacKenzie. It concatenates and prints files in reverse order.
ie., stdout of the command is given as standard Input to tac and it copies standard input to standard output reversing the records each line by separately.
Step 1: List files in the default order.
[root@ssl httpd]$ ls -rlt total 12 lrwxrwxrwx 1 root root 29 Sep 8 15:58 modules -> ../../usr/lib64/httpd/modules lrwxrwxrwx 1 root root 19 Sep 8 15:58 logs -> ../../var/log/httpd drwxr-xr-x 2 root root 4096 Sep 8 15:58 conf lrwxrwxrwx 1 root root 10 Sep 8 15:58 run -> /run/httpd drwxr-xr-x 2 root root 4096 Nov 28 16:41 conf.modules.d drwxr-xr-x 2 root root 4096 Nov 28 16:41 conf.d
Step 2: List files in the reverse order of their default order.
[root@ssl httpd]$ ls -lrt | tac drwxr-xr-x 2 root root 4096 Nov 28 16:41 conf.d drwxr-xr-x 2 root root 4096 Nov 28 16:41 conf.modules.d lrwxrwxrwx 1 root root 10 Sep 8 15:58 run -> /run/httpd drwxr-xr-x 2 root root 4096 Sep 8 15:58 conf lrwxrwxrwx 1 root root 19 Sep 8 15:58 logs -> ../../var/log/httpd lrwxrwxrwx 1 root root 29 Sep 8 15:58 modules -> ../../usr/lib64/httpd/modules
This built-in command tac
can be used on any Linux command or on your own scripts as well.