Sort Directory Contents From the Command Line in Linux
I was trying to make since of some apache error logs and was trying to find latest files. Typically I would just use ls -l (to list all of the files in long format) and find the file that comes closest to matching the estimated time of the error, in this case I’m on a development machine which tend to result in a lot of errors. Since there are several error logs in the /var/logs directory I wanted to sort these by date so I could get see, at a glance, when errors are happening. What I found was the following.
ls -rlt
Running the ls -rlt will return all of the files in a target directory sorted like the reverse chronological order.
-rw-r----- 1 root adm 32435 Dec 1 07:47 ssl_access.log.3.gz
-rw-r----- 1 root adm 1480 Dec 1 07:47 error.log.4.gz
-rw-r----- 1 root adm 5179 Dec 5 18:39 access.log.2.gz
-rw-r----- 1 root adm 17512 Dec 6 17:58 ssl_access.log.2.gz
-rw-r----- 1 root adm 379 Dec 8 09:24 other_vhosts_access.log.3.gz
-rw-r----- 1 root adm 4210 Dec 8 09:24 error.log.3.gz
-rw-r----- 1 root adm 223281 Dec 18 07:42 access.log.1
-rw-r----- 1 root adm 11431859 Dec 18 08:16 ssl_access.log.1
-rw-r----- 1 root adm 0 Dec 18 11:49 ssl_access.log
-rw-r----- 1 root adm 0 Dec 18 11:49 access.log
-rw-r----- 1 root adm 797 Dec 18 11:49 other_vhosts_access.log.2.gz
-rw-r----- 1 root adm 26752 Dec 18 11:49 error.log.2.gz
-rw-r----- 1 root adm 994 Dec 24 08:05 other_vhosts_access.log.1
-rw-r----- 1 root adm 1034 Dec 24 08:05 error.log.1
-rw-r----- 1 root adm 1420 Dec 25 07:40 other_vhosts_access.log
-rw-r----- 1 root adm 1546 Dec 25 07:40 error.log
ls and the -rlt arguments explained.
Usage: ls [OPTION]... [FILE]...
List information about the FILEs (the current directory by default).
Sort entries alphabetically if none of -cftuvSUX nor --sort is specified.
-l use a long listing format
-r reverse order while sorting
-t sort by modification time, newest first
Sources
- ls man pages ls –help from a Linux command line.