How to Sort ls Command by Date
The ‘ls’ command lists all files and folders in a directory at the command line, but by default ls returns a list in alphabetical order. With a simple command flag, you can have ls sort by date instead, showing the most recently modified items at the top of the ls command results. This trick applies to the ls command output in Mac OS / Mac OS X, Linux, BSD, as well as Bash in Windows.
The -t flag will sort ls command output by last modified date and time, but for best results you’ll likely want to apply it with the -l long listing flag, and perhaps a few others as well. Let’s review a few helpful ways to sort ls output by date.
Sort ‘ls’ Output by Date
The -t flag will sort the ls command output by last date and time modified:
- Open the Terminal if you have not done so already (/Applications/Utilities/ in mac OS) and navigate to the directory you wish to sort by date with ls
- Issue the following command syntax:
- Hit return to see the directory contents listed with ls by date
The most recently modified items will be shown at the top of the command output, rather than showing the returned list in alphabetical order.
Show ls Sort by Date, Human Readable, All Files
My personal preference for sorting ls output by date modified is to use -lt but also include -h for human readable sizes, and -a for showing all dot prefixed files as well. This also makes it an easy to remember flag of -halt, used like so:
Reversing ls Sort by Date Output
If you want to reverse the order so that the most recently modified items are on the bottom of the ls command output, you can add the -r flag as well like so:
The output will be same except it has been shown in reverse order, with oldest modified date on top and most recently modified date and time on the bottom.
This trick obviously applies to the command line and Terminal, but sorting by date and variations of date modified or last date opened can be incredibly useful for Finder as well. For example, sorting the Mac Finder ‘All My Files’ by last date opened is a great tip that can be similarly applied to any other folder shown in Finder on the Mac to show the last time a file was accessed or modified.
Have any other helpful tips or tricks for sorting directories by date? Let us know in the comments below.