Linux find date time

How to display modified date time with ‘find’ command?

With a find command, I can display directories names with multiple levels. The following command display all directories under /var path with a depth of 2:

find /var -maxdepth 2 -type d; 
/var /var/log /var/log/sssd /var/log/samba /var/log/audit /var/log/ConsoleKit /var/log/gdm /var/log/sa 
stat /var/log/samba | grep 'Modify:' 
Modify: 2014-01-02 11:21:27.762346214 -0800 

Is there a way to combine the two commands so that directories will be listed with modified date time?

6 Answers 6

The accepted answer works but it’s slow. There’s no need to exec stat for each directory, find provides the modification date and you can just print it out directly. Here’s an equivalent command that’s considerably faster:

 find /var -maxdepth 2 -type d -printf "%p %TY-%Tm-%Td %TH:%TM:%TS %Tz\n" 

A much better solution. It also works with the find from msys running on Windows, which lacks a stat command.

More helpful links for explanation of % formatters. unix.stackexchange.com/a/215236/216480 or on the man page search for «-printf format»

While the format string «%p %Tc» does work, it formats the output slightly differently. E.g. «/var/spool Mon 29 Sep 2014 09:05:54 BST» instead of «/var/spool 2014-09-29 09:05:54.000000000 +0100».

You could use the -exec switch for find and define the output format of stat using the -c switch as follows:

find /var -maxdepth 2 -type d -exec stat -c «%n %y» <> \;

This should give the filename followed by its modification time on the same line of the output.

The -printf option below avoids calling stat for every file found. In my test the command yields almost identical output, just an extra digit’s precision on the seconds.

For MacOS the format arg character for stat is -f . find /var -maxdepth 2 -type d -exec stat -f «%t%Sm %N» <> \;

Recent GNU versions of find also include a -printf option which includes date fields. If you need to print the file’s name and modification time in the standard «C» format, you can use -printf «%c %p\n» .

If you want the date in a specific format, you can use the %C followed by a field character. For example, 4-digit year would be %CY , with Y being the character for 4-digit year.
Note that if you need multiple fields, you’ll need to specify %C multiple times. For example, YYYY-MM-DD format would look like %CY-%Cm-%Cd .

Check the man pages or online documentation for additional details.

Here is a working example:

find . -name favicon.ico -printf "%c %p\n" 

Источник

Поиск в Linux с помощью команды find

Обновлено

Обновлено: 01.02.2022 Опубликовано: 25.07.2016

Утилита find представляет универсальный и функциональный способ для поиска в Linux. Данная статья является шпаргалкой с описанием и примерами ее использования.

Общий синтаксис

путь к корневому каталогу, откуда начинать поиск. Например, find /home/user — искать в соответствующем каталоге. Для текущего каталога нужно использовать точку «.». набор правил, по которым выполнять поиск. * по умолчанию, поиск рекурсивный. Для поиска в конкретном каталоге можно использовать опцию maxdepth.

Описание опций

Также доступны логические операторы:

Читайте также:  Linux change audio output
Оператор Описание
-a Логическое И. Объединяем несколько критериев поиска.
-o Логическое ИЛИ. Позволяем команде find выполнить поиск на основе одного из критериев поиска.
-not или ! Логическое НЕ. Инвертирует критерий поиска.

Полный набор актуальных опций можно получить командой man find.

Примеры использования find

Поиск файла по имени

* в данном примере будет выполнен поиск файла с именем file.txt по всей файловой системе, начинающейся с корня /.

2. Поиск файла по части имени:

* данной командой будет выполнен поиск всех папок или файлов в корневой директории /, заканчивающихся на .tmp

а) Логическое И. Например, файлы, которые начинаются на sess_ и заканчиваются на cd:

find . -name «sess_*» -a -name «*cd»

б) Логическое ИЛИ. Например, файлы, которые начинаются на sess_ или заканчиваются на cd:

find . -name «sess_*» -o -name «*cd»

в) Более компактный вид имеют регулярные выражения, например:

* где в первом поиске применяется выражение, аналогичное примеру а), а во втором — б).

4. Найти все файлы, кроме .log:

* в данном примере мы воспользовались логическим оператором !.

Поиск по дате

1. Поиск файлов, которые менялись определенное количество дней назад:

* данная команда найдет файлы, которые менялись более 60 дней назад.

find . -mmin -20 -mmin +10 -type f

* найти все файлы, которые менялись более 10 минут, но не более 20-и.

2. Поиск файлов с помощью newer. Данная опция доступна с версии 4.3.3 (посмотреть можно командой find —version).

find . -type f -newermt «2019-11-02 00:00»

* покажет все файлы, которые менялись, начиная с 02.11.2019 00:00.

find . -type f -newermt 2019-10-31 ! -newermt 2019-11-02

* найдет все файлы, которые менялись в промежутке между 31.10.2019 и 01.11.2019 (включительно).

find . -type f -newerat 2019-10-08

* все файлы, к которым обращались с 08.10.2019.

find . -type f -newerat 2019-10-01 ! -newerat 2019-11-01

* все файлы, к которым обращались в октябре.

find . -type f -newerct 2019-09-07

* все файлы, созданные с 07 сентября 2019 года.

find . -type f -newerct 2019-09-07 ! -newerct «2019-09-09 07:50:00»

* файлы, созданные с 07.09.2019 00:00:00 по 09.09.2019 07:50

По типу

Искать в текущей директории и всех ее подпапках только файлы:

* f — искать только файлы.

Поиск по правам доступа

1. Ищем все справами на чтение и запись:

2. Находим файлы, доступ к которым имеет только владелец:

Поиск файла по содержимому

find / -type f -exec grep -i -H «content» <> \;

* в данном примере выполнен рекурсивный поиск всех файлов в директории / и выведен список тех, в которых содержится строка content.

С сортировкой по дате модификации

find /data -type f -printf ‘%TY-%Tm-%Td %TT %p\n’ | sort -r

* команда найдет все файлы в каталоге /data, добавит к имени дату модификации и отсортирует данные по имени. В итоге получаем, что файлы будут идти в порядке их изменения.

Лимит на количество выводимых результатов

Самый распространенный пример — вывести один файл, который последний раз был модифицирован. Берем пример с сортировкой и добавляем следующее:

find /data -type f -printf ‘%TY-%Tm-%Td %TT %p\n’ | sort -r | head -n 1

Поиск с действием (exec)

1. Найти только файлы, которые начинаются на sess_ и удалить их:

find . -name «sess_*» -type f -print -exec rm <> \;

* -print использовать не обязательно, но он покажет все, что будет удаляться, поэтому данную опцию удобно использовать, когда команда выполняется вручную.

2. Переименовать найденные файлы:

find . -name «sess_*» -type f -exec mv <> new_name \;

Читайте также:  Linux скопировать права доступа

find . -name «sess_*» -type f | xargs -I ‘<>‘ mv <> new_name

3. Переместить найденные файлы:

find . -name «sess_*» -type f -exec mv <> /new/path/ \;

* в данном примере мы переместим все найденные файлы в каталог /new/path/.

4. Вывести на экран количество найденных файлов и папок, которые заканчиваются на .tmp:

find /home/user/* -type d -exec chmod 2700 <> \;

* в данном примере мы ищем все каталоги (type d) в директории /home/user и ставим для них права 2700.

6. Передать найденные файлы конвееру (pipe):

find /etc -name ‘*.conf’ -follow -type f -exec cat <> \; | grep ‘test’

* в данном примере мы использовали find для поиска строки test в файлах, которые находятся в каталоге /etc, и название которых заканчивается на .conf. Для этого мы передали список найденных файлов команде grep, которая уже и выполнила поиск по содержимому данных файлов.

7. Произвести замену в файлах с помощью команды sed:

find /opt/project -type f -exec sed -i -e «s/test/production/g» <> \;

* находим все файлы в каталоге /opt/project и меняем их содержимое с test на production.

Чистка по расписанию

Команду find удобно использовать для автоматического удаления устаревших файлов.

Открываем на редактирование задания cron:

0 0 * * * /bin/find /tmp -mtime +14 -exec rm <> \;

* в данном примере мы удаляем все файлы и папки из каталога /tmp, которые старше 14 дней. Задание запускается каждый день в 00:00.
* полный путь к исполняемому файлу find смотрим командой which find — в разных UNIX системах он может располагаться в разных местах.

Источник

How to Find Files Based on Timestamp in Linux

The find command in Linux is used to search for files and folders based on different parameters. These parameters can be the filename, size, type of file, etc.

One such parameter is the timestamp of the file. In Linux (and all Unix based file systems) there are 3 timestamps maintained for every file:

  1. Last Modification Time
  2. Last Access Time
  3. Last Status Change Time (i.e., when metadata of the file like permissions are changed)

Let’s see how to use find to search for files based on each of these timestamps.

Find File Timestamps in Linux

First of all, we can run the ‘stat‘ command in Linux to get all these timestamps for a file. For example for a file with the name ‘stat‘, run:

Find Stat Timestamps

Find Files Based on Timestamp

Now, to find files based on the timestamp, we use the argument ‘-newerXY’ of find from the man page.

Man Page of Find Command

Thus in the argument ‘-newerXY’ , we can have X as a, c, or m, respectively for last access, last status change, and last modification times, and Y as t, so that we can have the next argument to be a timestamp string.

Note: The birth time, i.e. creation time of a file is not maintained in Unix based file systems

To generalize, the command to be run looks like this:

Here, the format of the timestamp should be: ‘YYYY-MM-DD HH:MM:SS’.

Let’s try this on a folder with few files and only two files having accessed, modified and status changed after a specified time.

find . -newerat ‘2021-02-19 06:34’ find . -newerct ‘2021-02-19 06:34’ find . -newermt ‘2021-02-19 06:34’

Find Files Based on Timestamp

Verify with ‘stat’ if the timestamps of both files are indeed greater than the specified time.

Verify File Timestamp

Conclusion

We have learned how to use the ‘-newerXY’ the argument of command find to search for files based on timestamp.

Читайте также:  Canon lbp 2900b драйвер linux

Note that you can also use another file for a reference timestamp instead of explicitly specifying the timestamp, in which case the ‘t’ from the argument can be skipped.

Thanks a lot for reading and let us know your thoughts in the comments below!

Источник

How do I find all the files that were created today in Unix/Linux?

On my Fedora 10 system, with findutils-4.4.0-1.fc10.i386 :

find -daystart -ctime 0 -print 

The -daystart flag tells it to calculate from the start of today instead of from 24 hours ago.

Note however that this will actually list files created or modified in the last day. find has no options that look at the true creation date of the file.

That is almost perfect for me, clean and concise, just missing the «-f» flag to get only files (without current dir)

(@ephemient: Well, with *nix, the ctime of an inode was colloquially known as the creation time, even if the specification said (inode) change time (keeping neither changes to file names nor contents, but meta data like ownership, permissions,…. sleuthkit on «MAC» meaning))

find . -mtime -1 -type f -print 

Don’t use backticks; don’t use pwd except for printing (that’s the p in pwd ) the working directory. Use . to reference current directory.

this answer is incorrect — this displays the files created in the last 24 hours, not the files created today

@G.Lebret -ctime is the time the file’s status was last changed. Unix doesn’t store file creation time, last modified time is obviously equivalent to creation time if nothing modified the file after it was created.

To find all files that are modified today only (since start of day only, i.e. 12 am), in current directory and its sub-directories:

touch -t `date +%m%d0000` /tmp/$$ find . -type f -newer /tmp/$$ rm /tmp/$$ 

I use this with some frequency:

$ ls -altrh --time-style=+%D | grep $(date +%D) 

After going through many posts I found the best one that really works

find $file_path -type f -name "*.txt" -mtime -1 -printf "%f\n" 

This prints only the file name like abc.txt not the /path/tofolder/abc.txt

Also also play around or customize with -mtime -1

This worked for me. Lists the files created on May 30 in the current directory.

Use ls or find to have all the files that were created today.

Using ls : ls -ltr | grep «$(date ‘+%b %e’)»

Using find : cd $YOUR_DIRECTORY ; find . -ls 2>/dev/null| grep «$(date ‘+%b %e’)»

 find ./ -maxdepth 1 -type f -execdir basename '<>' ';' | grep `date +'%Y%m%d'` 

Welcome to Stack Overflow. Code dumps without any explanation are rarely helpful. Stack Overflow is about learning, not providing snippets to blindly copy and paste. Please edit your question and explain how it answers the specific question being asked. See How to Answer. This is especially important when answering old questions (this one is over 12 years old) with existing answers.

You can use find and ls to accomplish with this:

find . -type f -exec ls -l <> \; | egrep "Aug 26"; 

It will find all files in this directory, display useful informations ( -l ) and filter the lines with some date you want. It may be a little bit slow, but still useful in some cases.

Источник

Оцените статью
Adblock
detector