How can I sort the output of ‘ls’ by last modified date?
How can I sort the output of ls by last modified date?
10 Answers 10
or (for reverse, most recent at bottom):
The ls man page describes this in more details, and lists other options.
Try this: ls -ltr . It will give you the recent to the end of the list
For a complete answer here is what I use: ls -lrth
Put this in your startup script /etc/bashrc and assign an alias like this: alias l=’ls -lrth’ Restart your terminal and you should be able to type l and see a long list of files.
/.bash_aliases just for your user (one can create the file if it doesn’t exist already – Dinei Apr 24 ’18 at 1:23
I use sometime this:
to look recursively about which files was modified in last 5 minutes.
. or now, with recent version of GNU find:
. and even for not limiting to files:
(note the -d switch to ls for not displaying content of directories)
More robust way?
Mnemonic
For don’t ignore entries starting with . and sort by date (newest first):
For don’t ignore entries starting with . and reverse sort by date (oldest first):
For don’t ignore entries starting with . , use a long listing format and sort by date (newest first):
For print human readable sizes, don’t ignore entries starting with . , use a long listing format and sort by date (newest first) (@EvgeniSergeev note):
but be careful with the last one, because a simple mistype can cause a server crash. (@Isaac note)
Вывод списка файлов с сортировкой
Поделюсь удобными параметрами команды ls для сортировки списка файлов. Команда ls предназначена для вывода списка файлов и директорий, но по умолчанию она сортирует список по имени.
Для того, чтобы отсортировать список файлов используются следующие опции:
Опция | Эквивалентная опция | Описание |
---|---|---|
-U | —sort=none | без сортировки |
-X | —sort=extension | сортировка по расширению файла |
-S | —sort=size | сортировка по размеру |
-t | —sort=time | сортировка по времени изменения |
-v | выполнять сортировку по версиям файлов | |
-r | выполнять сортировку в обратном порядке |
Например, мы хотим отсортировать список по размеру файлов, тогда выполняем команду:
Это эквивалентно следующей команде:
Аналогично, например, если мы хотим получить список, отсортированный по расширению файлов:
Вывод директорий над файлами
Обычно команда ls выводит директории вперемешку с файлами. Некоторые реализации команды ls поддерживают полезную опцию: —group-directories-first. Если данная опция указана, то все директории будут выводится над списком файлов, что очень удобно.
Дополнительную информацию по команде ls вы можете получить, выполнив в терминале: man ls.
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:
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.
How to Sort Output of ‘ls’ Command By Last Modified Date and Time
One of the commonest things a Linux user will always do on the command line is listing the contents of a directory. As we may already know, ls and dir are the two commands available on Linux for listing directory content, with the former being more popular and in most cases, preferred by users.
When listing directory contents, the results can be sorted based on several criteria such as alphabetical order of filenames, modification time, access time, version and file size. Sorting using each of these file properties can be enabled by using a specific flag.
In this brief ls command guide, we will look at how to sort the output of ls command by last modification time (date and time).
Let us start by executing some basic ls commands.
Linux Basic ls Commands
1. Running ls command without appending any argument will list current working directory contents.
List Content of Working Directory
2. To list contents of any directory, for example /etc directory use:
List Contents of Directory
3. A directory always contains a few hidden files (at least two), therefore, to show all files in a directory, use the -a or —all flag:
List Hidden Files in Directory
4. You can as well print detailed information about each file in the ls output, such as the file permissions, number of links, owner’s name and group owner, file size, time of last modification and the file/directory name.
This is activated by the -l option, which means a long listing format as in the next screenshot:
Long List Directory Contents
Sort Files Based on Time and Date
5. To list files in a directory and sort them last modified date and time, make use of the -t option as in the command below:
Sort ls Output by Date and Time
6. If you want a reverse sorting files based on date and time, you can use the -r option to work like so:
Sort ls Output Reverse by Date and Time
We will end here for now, however, there is more usage information and options in the ls command, so make it a point to look through it or any other guides offering ls command tricks every Linux user should know or use sort command. Last but not least, you can reach us via the feedback section below.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.