- How to Find and Sort Files Based on Modification Date and Time in Linux
- Linux Utilities to Sort Files in Linux
- ls command
- sort command
- Some Ways to Sort Files using Date and Time
- 1. List Files Based on Modification Time
- 2. List Files Based on Last Access Time
- 3. List Files Based on Last Modification Time
- 4. Sorting Files based on Month
- 5. Sort Files Based on Date
- 6. Sorting Files Based on Time
- 7. Sorting Ouptut of ls -l based on Date
- Conclusion
- If You Appreciate What We Do Here On TecMint, You Should Consider:
- Unix / Linux найти и отсортировать по дате изменения
- Find And Sort Files Based On Access, Modification Date And Time In Linux
- Find and sort files based on access, modification date and time in Linux
- 1. Find and sort files based on last access time using ls command
- 2. Find and sort files based on modification time using ls command
- 3. Find and sort files based on last modification time using ls command
- 4. Find and sort files based on date
- Как найти и отсортировать файлы по дате и времени модификации в Linux
- Утилиты Linux для сортировки файлов в Linux
- Некоторые способы сортировки файлов по дате и времени
- Заключение
How to Find and Sort Files Based on Modification Date and Time in Linux
Usually, we are in habit of saving a lot of information in form of files on our system. Some, hidden files, some kept in a separate folder created for our ease of understanding, while some as it is. But, this whole stuff fills our directories; usually desktop, making it look like a mess. But, the problem arises when we need to search for a particular file modified on particular date and time in this huge collection.
Find and Sort Files by Date and Time in Linux
People comfortable with GUI’s can find it using File Manager, which lists files in long listing format, making it easy to figure out what we wanted, but those users having habit of black screens, or even anyone working on servers which are devoid of GUI’s would want a simple command or set of commands that could ease out their search.
Real beauty of Linux shows here, as Linux has a collection of commands which if used separately or together can help to search for a file, or sort a collection of files according to their name, date of modification, time of creation, or even any filter you could think of applying to get your result.
Here, we will unveil the real strength of Linux by examining a set of commands which can help sorting a file or even a list of files by Date and Time.
Linux Utilities to Sort Files in Linux
Some basic Linux command line utilities that are just sufficient for sorting a directory based on Date and Time are:
ls command
ls – Listing contents of directory, this utility can list the files and directories and can even list all the status information about them including: date and time of modification or access, permissions, size, owner, group etc.
We’ve already covered many articles on Linux ls command and sort command, you can find them below:
sort command
sort – This command can be used to sort the output of any search just by any field or any particular column of the field.
We’ve already covered two articles on Linux sort command, you can find them below:
These commands are in themselves very powerful commands to master if you work on black screens and have to deal with lots of files, just to get the one you want.
Some Ways to Sort Files using Date and Time
Below are the list of commands to sort based on Date and Time.
1. List Files Based on Modification Time
The below command lists files in long listing format, and sorts files based on modification time, newest first. To sort in reverse order, use ‘-r’ switch with this command.
2. List Files Based on Last Access Time
Listing of files in directory based on last access time, i.e. based on time the file was last accessed, not modified.
3. List Files Based on Last Modification Time
Listing of files in directory based on last modification time of file’s status information, or the ‘ctime’ . This command would list that file first whose any status information like: owner, group, permissions, size etc has been recently changed.
If ‘-a’ switch is used with above commands, they can list and sort even the hidden files in current directory, and ‘-r’ switch lists the output in reverse order.
For more in-depth sorting, like sorting on Output of find command, however ls can also be used, but there ‘sort’ proves more helpful as the output may not have only file name but any fields desired by user.
Below commands show usage of sort with find command to sort the list of files based on Date and Time.
To learn more about find command, follow this link: 35 Practical Examples of ‘find’ Command in Linux
4. Sorting Files based on Month
Here, we use find command to find all files in root (‘/’) directory and then print the result as: Month in which file was accessed and then filename. Of that complete result, here we list out top 11 entries.
The below command sorts the output using key as first field, specified by ‘-k1’ and then it sorts on Month as specified by ‘M’ ahead of it.
5. Sort Files Based on Date
Here, again we use find command to find all the files in root directory, but now we will print the result as: last date the file was accessed, last time the file was accessed and then filename. Of that we take out top 11 entries.
The below sort command first sorts on basis of last digit of the year, then sorts on basis of last digit of month in reverse order and finally sorts on basis of first field. Here, ‘1.8‘ means 8th column of first field and ‘n’ ahead of it means numerical sort, while ‘r’ indicates reverse order sorting.
6. Sorting Files Based on Time
Here, again we use find command to list out top 11 files in root directory and print the result in format: last time file was accessed and then filename.
The below command sorts the output based on first column of the first field of the output which is first digit of hour.
7. Sorting Ouptut of ls -l based on Date
This command sorts the output of ‘ls -l’ command based on 6th field month wise, then based on 7th field which is date, numerically.
Conclusion
Likewise, by having some knowledge of sort command, you can sort almost any listing based on any field and even its any column you desire. These were some of tricks to help you sort files based on Date or Time. You can have your own tricks build based on these. However, if you have any other interesting trick, you can always mention that in your comments.
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.
Источник
Unix / Linux найти и отсортировать по дате изменения
Как я могу сделать простой, find который бы упорядочил результаты по самым последним модифицированным?
Вот текущий ток, который find я использую (я делаю экранирование оболочки в PHP, так что это аргумент для переменных):
Как я мог иметь этот порядок поиска по самым последним модифицированным? (Обратите внимание, я не хочу, чтобы он сортировал «после» поиска, а скорее находил результаты на основе того, что было недавно изменено.)
printf аргументы от man find :
%Tk : Время последнего изменения файла в формате, указанном k .
@ : секунды с 1 января 1970 года, 00:00 по Гринвичу, с дробной частью.
c : дата и время локали (сб. 04 ноября 12:02:33 EST 1989).
/.zshrc : fr () < find ./ -iname "*"$@"*" -printf "%T@ %Td-%Tb-%TY %Tk:%TM %p\n" | sort -n | cut -d " " -f 2- | grep -i "$@" ; >он рекурсивно находит все файлы, содержащие шаблон первого аргумента, переданного команде ( fr
), и сортирует их по последнему последнему.
Самый простой способ — использовать zsh благодаря его квалификаторам glob .
Если у вас есть GNU find, заставьте его распечатать время изменения файла и отсортировать по нему.
Если у вас есть GNU find, но нет других утилит GNU, используйте символы новой строки вместо разделителей; вы потеряете поддержку имен файлов, содержащих переводы строк.
Если у вас есть Perl (здесь я предполагаю, что в именах файлов нет новых строк):
Если у вас есть Python (также предполагается, что в именах файлов нет перевода строки):
Вероятно, есть способ сделать то же самое в PHP, но я этого не знаю.
Если вы хотите работать только с инструментами POSIX, это довольно сложно; см. Как вывести список файлов, отсортированных по дате изменения рекурсивно (команда stat недоступна!) (повторная установка первых 10 — самая простая часть).
Вам не нужен PHP или Python, просто ls :
Если команда * завершается со статусом ошибки (т. Е. Список аргументов слишком длинный ), вы можете выполнить итерацию с помощью команды find. Перефразировано из: Максимальная длина аргументов для нового процесса
- find . -print0|xargs -0 command (оптимизирует скорость, если find не реализует «-exec +», но знает «-print0»)
- find . -print|xargs command (если в аргументах нет пробелов)
Если основная часть аргументов состоит из длинных, абсолютных или относительных путей, попробуйте переместить ваши действия в каталог. cd /directory/with/long/path; command * И еще одно быстрое решение может состоять в том, чтобы соответствовать меньшему количеству аргументов: command [a-e]*; command [f-m]*; .
Вам нужно только LS
Вы можете сделать, find /wherever/your/files/hide -type f -exec ls -1rt «<>» +; как указано выше,
Для каждого файла сначала выводится числовая временная метка (для сортировки с последующим табулированием \t ), затем удобочитаемая временная метка, затем размер файла (к сожалению, find это -printf невозможно в мегабайтах, только в кибибайтах), затем имя файла с относительным дорожка.
Затем sort -n сортирует его по первому числовому полю.
Затем cut избавляется от того первого числового поля, которое не представляет интереса для пользователя. (Печатает второе поле вперед.) Разделителем полей по умолчанию является \t или табуляция.
Я намеренно сделал поле размера файла 6 символов, потому что, если сделать его длиннее, становится трудно визуально различать, насколько большие файлы. Таким образом, файлы размером больше 1e6 КиБ выделяются: на 1 символ — 1-9 ГБ, на 2 символа — 10-99 ГБ и т. Д.
Изменить: вот еще одна версия (так как происходит find . -printf «%Tc» сбой на MinGW / MSYS):
Давать вывод как:
-I<> вызывает вхождение <> аргумента в качестве аргумента, и теперь новые строки являются разделителями аргументов (обратите внимание на пробелы в именах файлов выше).
ls -G подавляет печать имени группы (пустая трата места).
ls -h —si производит удобочитаемые размеры файлов (более правильно с —si ).
ls -t сортирует по времени, что здесь не имеет значения, но это то, что я обычно использую.
Источник
Find And Sort Files Based On Access, Modification Date And Time In Linux
We already know how to organize the similar type of files in specific folders in Linux and Unix-like operating systems. In that method, we learned to organize the similar type of files in a folder. In other words, the files have been organized based on their extension. We don’t know whether the file is new or old one. We simply put the same type of files in a folder. Today, in this guide, we are going to find and sort files based on access and modification date and time, not extension. In case, if you want to find a particular file accessed or modified on a particular date or time, you’re on the right track. Read on.
Find and sort files based on access, modification date and time in Linux
You don’t need to install any extra applications to find and sort files. For the purpose of this guide, we are going to use three Linux commands namely ls, find and sort. These commands are the part of Linux Kernel, so don’t bother installing them.
As may already know, the ls command lists a directory contents with additional information such as date and time of modification or access, permissions, size, owner, group etc. It will sort the entries of the given directory, alphabetically. If you didn’t mention the directory, it will list the contents of current working directory.
The find command is used to search for files in a directory hierarchy.
The sort command sorts the lines of text files and writes sorted concatenation of all FILE(s) to standard output.
1. Find and sort files based on last access time using ls command
The following command will list files based on the last access time. The newest files will be listed first.
Sample output:
- -u — Sort by access time, newest first
2. Find and sort files based on modification time using ls command
To list files based on the modification time, run:
- -l — Indicates long listing format,
- -t — Sort by modification time, newest first.
Sample output:
The above command will sort the files of the current working directory based on the modification time. The newest files will be displayed first.
To list the files of a specific directory based on modification time, type:
To list the files in reverse order, i.e oldest files first, use ‘r’ flag like below:
3. Find and sort files based on last modification time using ls command
The command lists the files based on the last modification time. It means, this command lists the files first whose any status information (such as owner, group, permissions, size etc) have been recently changed.
Sample output:
- -c — Sort by last modification time
4. Find and sort files based on date
The following command lists the files based on last accessed date and time. Newest files will be listed first.
Sample output:
In the above output, the first column shows the last accessed date of the file, second column shows the last accessed time and third column shows the name of file. Here, ‘head -n 10’ is not the number files. It is number of entries in the output including the blank spaces.
Also, you can use «sort» command with «ls» command to list the files based on last accessed month, date, and time like below.
Sample output:
- -k6M — Lists files monthly wise (6th field) in the output.
- -k7n — Lists files date wise (7th field) in the output.
And, that’s all. You know now how to find and sort files based on the access, modification time and date in Linux. As you can see in the above examples, it is fairly easy to sort the files. For more details, refer man pages of each command.
Источник
Как найти и отсортировать файлы по дате и времени модификации в Linux
Обычно у нас есть привычка сохранять много информации в виде файлов в нашей системе. Некоторые, скрытые файлы, некоторые хранятся в отдельной папке, созданной для простоты понимания, а некоторые как есть. Но все это заполняет наши каталоги; обычно настольный, что делает его похожим на беспорядок. Но проблема возникает, когда нам нужно найти конкретный файл, измененный в определенную дату и время в этой огромной коллекции.
Люди, знакомые с графическим интерфейсом пользователя, могут найти его с помощью диспетчера файлов, который перечисляет файлы в формате длинного списка, что позволяет легко понять, что мы хотели, но те пользователи, у которых есть привычка к черным экранам, или даже любой, кто работает на серверах, которые лишены графического интерфейса, будут нужна простая команда или набор команд, которые могли бы облегчить их поиск.
Настоящая красота Linux проявляется здесь, поскольку в Linux есть набор команд, которые при использовании по отдельности или вместе могут помочь в поиске файла или сортировке коллекции файлов по их имени, дате модификации, времени создания или даже любому другому. фильтр, который вы могли бы подумать о применении, чтобы получить свой результат.
Здесь мы раскроем реальную силу Linux, изучив набор команд, которые могут помочь отсортировать файл или даже список файлов по дате и времени.
Утилиты Linux для сортировки файлов в Linux
Вот некоторые базовые утилиты командной строки Linux, которых достаточно для сортировки каталога по дате и времени:
ls — перечисление содержимого каталога, эта утилита может отображать файлы и каталоги и даже может отображать всю информацию о их статусе, включая дату и время изменения или доступа, разрешения, размер, владельца, группу и т. д.
Мы уже рассмотрели множество статей о команде Linux ls и команде sort, вы можете найти их ниже:
- Изучите команду ls на 15 основных примерах
- Изучите 7 команд Advanced ls с примерами
- 15 полезных вопросов для собеседования по команде ls в Linux
sort — эту команду можно использовать для сортировки результатов любого поиска по любому полю или любому конкретному столбцу поля.
Мы уже рассмотрели две статьи о команде сортировки Linux, вы можете найти их ниже:
- 14 примеров команд «sort» в Linux — часть 1
- 7 полезных примеров команд Linux «sort» — часть 2
Эти команды сами по себе являются очень мощными командами, которые нужно освоить, если вы работаете на черных экранах и имеете дело с большим количеством файлов, просто чтобы получить тот, который вам нужен.
Некоторые способы сортировки файлов по дате и времени
Ниже приведен список команд для сортировки по дате и времени.
Приведенная ниже команда перечисляет файлы в формате длинного списка и сортирует файлы по времени модификации, начиная с самых новых. Для сортировки в обратном порядке используйте переключатель -r с этой командой.
Список файлов в каталоге на основе времени последнего доступа, т.е. на основе времени последнего доступа к файлу, а не изменения.
Список файлов в каталоге на основе времени последнего изменения информации о статусе файла или ctime . Эта команда сначала перечислит тот файл, любая информация о статусе которого, такая как: владелец, группа, разрешения, размер и т. Д., Была недавно изменена.
Если переключатель -a используется с вышеуказанными командами, они могут перечислять и сортировать даже скрытые файлы в текущем каталоге, а переключатель -r выводит вывод в обратном порядке.
Однако для более глубокой сортировки, такой как сортировка в выводе команды find, также можно использовать ls , но там sort оказывается более полезным, поскольку вывод может содержать не только файл имя, но любые поля по желанию пользователя.
Команды ниже показывают использование sort с командой find для сортировки списка файлов по дате и времени.
Чтобы узнать больше о команде find, перейдите по этой ссылке: 35 практических примеров команды find в Linux
Здесь мы используем команду find , чтобы найти все файлы в корневом каталоге (‘/’) , а затем распечатать результат как: месяц, в котором был осуществлен доступ к файлу, а затем имя файла. Из этого полного результата мы перечисляем 11 лучших записей.
Приведенная ниже команда сортирует вывод с использованием ключа в качестве первого поля, указанного в -k1 , а затем сортирует по месяцу, указанному перед ним M .
Здесь мы снова используем команду find , чтобы найти все файлы в корневом каталоге, но теперь мы распечатаем результат в виде: последней даты доступа к файлу, последнего доступа к файлу и затем имени файла. Из этого мы выберем 11 лучших записей.
Приведенная ниже команда сортировки сначала выполняет сортировку на основе последней цифры года, затем сортировку на основе последней цифры месяца в обратном порядке и, наконец, сортировку на основе первого поля. Здесь «1.8» означает 8-й столбец первого поля, а «n» перед ним означает числовую сортировку, а «r» указывает сортировку в обратном порядке.
Здесь мы снова используем команду find , чтобы вывести список из 11 файлов в корневом каталоге и распечатать результат в формате: время последнего обращения к файлу и затем имя файла.
Приведенная ниже команда сортирует вывод на основе первого столбца первого поля вывода, который является первой цифрой часа.
Эта команда сортирует вывод команды ls -l на основе 6-го поля по месяцам, а затем на основе 7-го поля, которое является датой, численно.
Заключение
Точно так же, обладая некоторыми знаниями о команде сортировки, вы можете отсортировать практически любой список на основе любого поля и даже любого столбца, который вам нужен. Это были некоторые приемы, которые помогут вам сортировать файлы по дате или времени. На их основе вы можете создавать свои собственные трюки. Однако, если у вас есть другой интересный трюк, вы всегда можете упомянуть об этом в своих комментариях.
Источник