- 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:
- Linux Find Files By Date And List Files Modified On a Specific Date
- ls command example to find files by date
- find Command Example
- Linux find file by date using the date command
- Say hello to -newerXY option for find command
- To see all files modified on the 24/Sep/2017 in the current directory:
- 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.
Источник
Linux Find Files By Date And List Files Modified On a Specific Date
H ow do I find files by date under UNIX and Linux system? How search for files that created on a specific date on Linux or Unix-like system? How to get a list all files that have been modified on a specific date on Linux or Unix?
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | No |
Requirements | Linux or Unix |
Est. reading time | 4 mintues |
Linux and UNIX like operating systems do not store file creation time. However, you can use file access and modification time and date to find out file by date. For example, one can list all files that have been modified on a specific date.
Let us see how to find file by date on Linux. You need to use the ls command and find command.
ls command example to find files by date
The syntax is as follows:
You need to use the grep command/egrep command to filter out info:
$ ls -lt /etc/ | grep filename
ls -lt /etc/ | grep ‘Jun 20’
A better and recommended solution is the find command:
find . -type f -ls |grep ‘2017’
find . -type f -ls |grep ‘filename’
find /etc/ -type f -ls |grep ’25 Sep’
find Command Example
If you need a specific date range many days ago, than consider using the find command. In this example find files modified between Jan/1/2007 and Jan/1/2008, in /data/images directory:
You can save list to a text file called output.txt as follows:
find /data/images -type f -newer /tmp/start -not -newer /tmp/end > output.txt
Linux find file by date using the date command
Gnu find as various command line option to list files by a modification and access date/time stamp.
Say hello to -newerXY option for find command
The syntax is as follows:
find /dir/ -type f -newerXY ‘yyyy-mm-dd’
find /dir/ -type f -newerXY ‘yyyy-mm-dd’ -ls
The letters X and Y can be any of the following letters:
- a – The access time of the file reference
- B – The birth time of the file reference
- c – The inode status change time of reference
- m – The modification time of the file reference
- t – reference is interpreted directly as a time
To see all files modified on the 24/Sep/2017 in the current directory:
find . -type f -newermt 2017-09-24
## pass the -ls option to list files in ls -l format ##
find . -type f -newermt 2017-09-24 -ls
OR
find . -type f -newermt 2017-09-24 ! -newermt 2017-09-25
find . -type f -newermt 2017-09-24 ! -newermt 2017-09-25 -ls
Sample outputs:
Источник
linux найти файлы по дате создания
Часто у меня спрашивают: «как по SSH получить в перечень файлов созданных на определенную дату?» или «у меня есть папка с большим количеством файлов. нужно найти в этой папке файлы с определенной датой и поместить их в архив. Как это можно сделать?» Все очень просто, и сейчас мы разберем несколько часто встречающихся запросов.
В оболочках, основанных на Linux операционных системах, таких как Debian, Ubuntu, Redhat или Centos мы можем в консоле задать следующие команды и посмотреть их выполнение:
показать текущую директорию
перейти в директорию ‘/home1’
перейти в директорию уровнем выше
перейти в директорию двумя уровнями выше
перейти в домашнюю директорию
перейти в домашнюю директорию пользователя user1
перейти в директорию, в которой находились до перехода в текущую директорию
отобразить содержимое текущей директории
отобразить содержимое текущей директории с добавлением к именам символов, характеризующих тип
показать детализированное представление файлов и директорий в текущей директории
показать скрытые файлы и директории в текущей директории
показать файлы и директории содержащие в имени цифры
du -sk * | sort -rn
отображает размер и имена файлов и директорий, с сортировкой по размеру
find / -name file1
найти файлы и директории с именем file1. Поиск начать с корня (/)
find / -user user1
найти файл и директорию принадлежащие пользователю user1. Поиск начать с корня (/)
find /home/user1 -name «*.php»
Найти все файлы и директории, имена которых оканчиваются на ‘. php’. Поиск начать с ‘/home/user1’
find /usr/cgi -type f -mtime -11
найти все файлы в ‘/usr/cgi’, созданные или изменённые в течении последних 11 дней
find /usr/bin -type f -atime +300
найти все файлы в ‘/usr/bin’, время последнего обращения к которым более 300 дней
rm -f file1 file2
удалить файл с именем ‘file1’ и ‘file2’
удалить директорию с именем ‘dir1’
удалить директорию с именем ‘dir1’ и рекурсивно всё её содержимое
rm -rf dir1 dir2
удалить две директории и рекурсивно их содержимое
Ну, и немного примеров:
подсчитать количество файлов в директории
ls -A | wc -l или find -type f | wc -l
находим все файлы в текущем каталоге и вывод отфильтровать по php и за дату Nov 2 2011 :
ls -alR | grep ‘Nov 2 2011’ | grep php или ls /home/user1 -alR | grep ‘Nov 2 2011’ | grep php
Внимательно смотрите на формат написания даты и количество пробелов
‘Nov . . 2 . . 2011’ ‘Nov.12 . . 2011’
Вы можете сначала дать команду без [| grep ‘Nov 2 2011’ ] , затем скопировав дату и повторив ее уже с фильтром. Или find -type f -depth -1 | xargs ls -l | grep php
Если нужно не углубляться в подкаталоги ниже третьего уровня, используйте опцию -depth -3 :
ls -alR -depth -3 | grep ‘Nov 2 2011’
тоже самое, только с find:
find -type f -depth -3 | xargs ls -l | grep ‘Nov 2 2011’ | grep php
» | xargs ls -l » — задаем вывод атрибутов файла
» grep ‘что-то в строках вывода’ » — задаем фильтрование по строке
и такое имеет место (найти файлы с 26 по 28 октября 2016) (не у всякого хостера работает newermt ):
find ./ -newermt ‘Oct 26 2016’ \! -newermt ‘Oct 28 2016’ -ls или find -newermt ‘Oct 27 2016’
тогда найти все файлы созданные после создания файла config.php (определите у себя подходящий по дате)
find -type f -newer /home/user1/config.php | xargs ls -l | grep php
найти все файлы и вывод отфильтровать по ‘цифра.php’:
find -type f | grep 4.php
найденное можно удалить вот так:
find -type f | xargs ls -l | grep ‘Nov 2 2011’ | grep php | xargs rm -f
find -type f | xargs ls -l | grep ‘Nov 2 2011’ | grep php -delete
find -type f | xargs ls -l | grep ‘Nov 2 2011’ | grep php -exec rm -f <> \;
или можете положить отобранные файлы в архив:
find /home/user1 -type f | xargs ls -l | grep ‘Nov 2 2011’ | grep php -exec tar -cvf archive.tar <> \;
find /home/user1 -newermt ‘Oct 27 2016’ | xargs tar -czvf файл.tar.gz
Ключи:
-name — искать по имени файла, при использовании подстановочных образцов параметр заключается в кавычки.
-type — тип искомого: f=файл, d=каталог, l=ссылка (link).
-user — владелец: имя пользователя или UID.
-group — владелец: группа пользователя или GID.
-perm — указываются права доступа.
-size — размер: указывается в 512-байтных блоках или байтах (признак байтов — символ «c» за числом).
-atime — время последнего обращения к файлу.
-ctime — время последнего изменения владельца или прав доступа к файлу.
-mtime — время последнего изменения файла.
-newer другой_файл — искать файлы созданные позже, чем другой_файл.
-delete — удалять найденные файлы.
-ls — генерирует вывод как команда ls -dgils.
-print — показывает на экране найденные файлы.
-exec command <> \; — выполняет над найденным файлом указанную команду; обратите внимание на синтаксис.
-ok — перед выполнением команды указанной в -exec, выдаёт запрос.
-depth — начинать поиск с самых глубоких уровней вложенности, а не с корня каталога.
-prune — используется, когда вы хотите исключить из поиска определённые каталоги.
N — количество дней.
Такие рассуждения и команды можете использовать для поиска файлов на сервере с вредоносным кодом. Примеры часто обнаруженных угроз смотрите — Как обнаружить зараженные файлы на своем на сайте и хостинге?
Иногда может потребоваться найти самые большие файлы в директории:
ls -lSrh
find / -mount -type f -ls 2> /dev/null | sort -rnk7 | head -10 | awk ‘
или в директории /home
find /home -mount -type f -ls 2> /dev/null | sort -rnk7 | head -10 | awk ‘
Или самые большие папки (директории):
du -kx | egrep -v «\./.+/» | sort -n
Источник