Find last hour linux

Содержание
  1. Find Files By Access, Modification Date / Time Under Linux or UNIX
  2. -daystart option
  3. 35 Practical Examples of Linux Find Command
  4. 1. Find Files Using Name in Current Directory
  5. 2. Find Files Under Home Directory
  6. 3. Find Files Using Name and Ignoring Case
  7. 4. Find Directories Using Name
  8. 5. Find PHP Files Using Name
  9. 6. Find all PHP Files in the Directory
  10. 7. Find Files With 777 Permissions
  11. 8. Find Files Without 777 Permissions
  12. 9. Find SGID Files with 644 Permissions
  13. 10. Find Sticky Bit Files with 551 Permissions
  14. 11. Find SUID Files
  15. 12. Find SGID Files
  16. 13. Find Read-Only Files
  17. 14. Find Executable Files
  18. 15. Find Files with 777 Permissions and Chmod to 644
  19. 16. Find Directories with 777 Permissions and Chmod to 755
  20. 17. Find and remove single File
  21. 18. Find and remove Multiple File
  22. 19. Find all Empty Files
  23. 20. Find all Empty Directories
  24. 21. File all Hidden Files
  25. 22. Find Single File Based on User
  26. 23. Find all Files Based on User
  27. 24. Find all Files Based on Group
  28. 25. Find Particular Files of User
  29. 26. Find Last 50 Days Modified Files
  30. 27. Find Last 50 Days Accessed Files
  31. 28. Find Last 50-100 Days Modified Files
  32. 29. Find Changed Files in Last 1 Hour
  33. 30. Find Modified Files in Last 1 Hour
  34. 31. Find Accessed Files in Last 1 Hour
  35. 32. Find 50MB Files
  36. 33. Find Size between 50MB – 100MB
  37. 34. Find and Delete 100MB Files
  38. 35. Find Specific Files and Delete
  39. If You Appreciate What We Do Here On TecMint, You Should Consider:
  40. linux-notes.org
  41. Добавить комментарий Отменить ответ
  42. Команда find в Linux
  43. Основная информация о Find
  44. Основные параметры команды find
  45. Критерии
  46. Примеры использования
  47. 1. Поиск всех файлов
  48. 2. Поиск файлов в определенной папке
  49. 3. Ограничение глубины поиска
  50. 4. Инвертирование шаблона
  51. 5. Несколько критериев
  52. 6. Несколько каталогов
  53. 7. Поиск скрытых файлов
  54. 8. Поиск по разрешениям
  55. 9. Поиск файлов в группах и пользователях
  56. 10. Поиск по дате модификации
  57. 11. Поиск файлов по размеру
  58. 12. Поиск пустых файлов и папок
  59. 13. Действия с найденными файлами
  60. Выводы

Find Files By Access, Modification Date / Time Under Linux or UNIX

I do not remember where I saved pdf and text files under Linux. I have downloaded files from the Internet a few months ago. How do I find my pdf or text files?

You need to use the find command. Each file has three time stamps, which record the last time that certain operations were performed on the file:

You can search for files whose time stamps are within a certain age range, or compare them to other time stamps.

You can use -mtime option. It returns list of file if the file was last accessed N*24 hours ago. For example to find file in last 2 months (60 days) you need to use -mtime +60 option.

  • -mtime +60 means you are looking for a file modified 60 days ago.
  • -mtime -60 means less than 60 days.
  • -mtime 60 If you skip + or – it means exactly 60 days.

So to find text files that were last modified 60 days ago, use
$ find /home/you -iname «*.txt» -mtime -60 -print

Display content of file on screen that were last modified 60 days ago, use
$ find /home/you -iname «*.txt» -mtime -60 -exec cat <> \;

Count total number of files using wc command
$ find /home/you -iname «*.txt» -mtime -60 | wc -l

You can also use access time to find out pdf files. Following command will print the list of all pdf file that were accessed in last 60 days:
$ find /home/you -iname «*.pdf» -atime -60 -type -f

List all mp3s that were accessed exactly 10 days ago:
$ find /home/you -iname «*.mp3» -atime 10 -type -f

There is also an option called -daystart. It measure times from the beginning of today rather than from 24 hours ago. So, to list the all mp3s in your home directory that were accessed yesterday, type the command
$ find /home/you -iname «*.mp3» -daystart -type f -mtime 1

  • -type f – Only search for files and not directories

-daystart option

The -daystart option is used to measure time from the beginning of the current day instead of 24 hours ago. Find out all perl (*.pl) file modified yesterday, enter:

Читайте также:  Install libxml2 on windows

Источник

35 Practical Examples of Linux Find Command

The Linux find command is one of the most important and frequently used command command-line utility in Unix-like operating systems. The find command is used to search and locate the list of files and directories based on conditions you specify for files that match the arguments.

find command can be used in a variety of conditions like you can find files by permissions, users, groups, file types, date, size, and other possible criteria.

Through this article, we are sharing our day-to-day Linux find command experience and its usage in the form of examples.

In this article, we will show you the most used 35 Find Commands Examples in Linux. We have divided the section into Five parts from basic to advance usage of the find command.

  • Part I: Basic Find Commands for Finding Files with Names
  • Part II: Find Files Based on their Permissions
  • Part III: Search Files Based On Owners and Groups
  • Part IV: Find Files and Directories Based on Date and Time
  • Part V: Find Files and Directories Based on Size
  • Part VI: Find Multiple Filenames in Linux

1. Find Files Using Name in Current Directory

Find all the files whose name is tecmint.txt in a current working directory.

2. Find Files Under Home Directory

Find all the files under /home directory with the name tecmint.txt.

3. Find Files Using Name and Ignoring Case

Find all the files whose name is tecmint.txt and contains both capital and small letters in /home directory.

4. Find Directories Using Name

Find all directories whose name is Tecmint in / directory.

5. Find PHP Files Using Name

Find all php files whose name is tecmint.php in a current working directory.

6. Find all PHP Files in the Directory

Find all php files in a directory.

7. Find Files With 777 Permissions

Find all the files whose permissions are 777.

8. Find Files Without 777 Permissions

Find all the files without permission 777.

9. Find SGID Files with 644 Permissions

Find all the SGID bit files whose permissions are set to 644.

10. Find Sticky Bit Files with 551 Permissions

Find all the Sticky Bit set files whose permission is 551.

11. Find SUID Files

Find all SUID set files.

12. Find SGID Files

Find all SGID set files.

13. Find Read-Only Files

Find all Read-Only files.

14. Find Executable Files

Find all Executable files.

15. Find Files with 777 Permissions and Chmod to 644

Find all 777 permission files and use the chmod command to set permissions to 644.

16. Find Directories with 777 Permissions and Chmod to 755

Find all 777 permission directories and use the chmod command to set permissions to 755.

17. Find and remove single File

To find a single file called tecmint.txt and remove it.

18. Find and remove Multiple File

To find and remove multiple files such as .mp3 or .txt, then use.

19. Find all Empty Files

To find all empty files under a certain path.

20. Find all Empty Directories

To file all empty directories under a certain path.

21. File all Hidden Files

To find all hidden files, use the below command.

22. Find Single File Based on User

To find all or single files called tecmint.txt under / root directory of owner root.

23. Find all Files Based on User

To find all files that belong to user Tecmint under /home directory.

24. Find all Files Based on Group

To find all files that belong to the group Developer under /home directory.

25. Find Particular Files of User

To find all .txt files of user Tecmint under /home directory.

26. Find Last 50 Days Modified Files

To find all the files which are modified 50 days back.

27. Find Last 50 Days Accessed Files

To find all the files which are accessed 50 days back.

28. Find Last 50-100 Days Modified Files

To find all the files which are modified more than 50 days back and less than 100 days.

29. Find Changed Files in Last 1 Hour

To find all the files which are changed in the last 1 hour.

Читайте также:  Windows 10 как отключить автозапуск устройства

30. Find Modified Files in Last 1 Hour

To find all the files which are modified in the last 1 hour.

31. Find Accessed Files in Last 1 Hour

To find all the files which are accessed in the last 1 hour.

32. Find 50MB Files

To find all 50MB files, use.

33. Find Size between 50MB – 100MB

To find all the files which are greater than 50MB and less than 100MB.

34. Find and Delete 100MB Files

To find all 100MB files and delete them using one single command.

35. Find Specific Files and Delete

Find all .mp3 files with more than 10MB and delete them using one single command.

That’s it, We are ending this post here, In our next article, we will discuss more other Linux commands in-depth with practical examples. Let us know your opinions on this article using our comment section.

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-notes.org

Иногда, нужно найти все измененные файлы или папки в Unix/Linux ОС и в моей статье «Поиск последних измененных файлов/папок в Unix/Linux» я расскажу как это сделать.

Чтобы найти все файлы, которые были изменены с момента определенного времени (т.е. час назад, день назад, 24 часа назад и так далее) в Unix и Linux имеется команда find и она очень пригодиться для таких целей.
Чтобы найти все файлы, которые были изменены в течение последних 24 часов (последний полный день) в текущем каталоге и в его подкаталогах, используйте:

Опция «-mtime -1» сообщает команде find искать модифицированные файлы за последние сутки (24 часа).
Опция «-print» сообщает «find» выводить файлы и их пути (где они лежат) и данную команду можно заменить на «-ls» если нужно вывести подробную информацию о файле.

Примеры:

Например нужно найти файлы, что были изменены за последние 30 минут в папке /home/captain:

И приведу пример подобного, но для папки:

Например нужно найти измененные файлы за 5 дней, но не включать в поиск вчерашний день (за последний день):

Для полного счастья, можно вывести время модификации и отсортировать по нему:

Чтобы ограничить уровень вложенности, добавьте параметр «-depth». Например, поиск с уровнем вложенности не более 3 папок:

Поиск файлов в /home/captain директории (и во всех ее подпапках) которые были изменены в течение последних 60 минут, и вывести их атрибуты:

В качестве альтернативы, вы можете использовать xargs команду, чтобы достичь того же:

Поиск последних измененных файлов/папок в Unix/Linux завершен.

Добавить комментарий Отменить ответ

Этот сайт использует Akismet для борьбы со спамом. Узнайте, как обрабатываются ваши данные комментариев.

Источник

Команда find в Linux

Очень важно уметь вовремя и очень быстро найти нужную информацию в системе. Конечно, все современные файловые менеджеры предлагают отличные функции поиска, но им не сравнится с поиском в терминале Linux. Он намного эффективнее и гибче обычного поиска, вы можете искать файлы не только по имени, но и по дате добавления, содержимому, а также использовать для поиска регулярные выражения. Кроме того, с найденными файлами можно сразу же выполнять необходимые действия.

В этой статье мы поговорим о поиске с помощью очень мощной команды find Linux, подробно разберем ее синтаксис, опции и рассмотрим несколько примеров.

Основная информация о Find

Find — это одна из наиболее важных и часто используемых утилит системы Linux. Это команда для поиска файлов и каталогов на основе специальных условий. Ее можно использовать в различных обстоятельствах, например, для поиска файлов по разрешениям, владельцам, группам, типу, размеру и другим подобным критериям.

Утилита find предустановлена по умолчанию во всех Linux дистрибутивах, поэтому вам не нужно будет устанавливать никаких дополнительных пакетов. Это очень важная находка для тех, кто хочет использовать командную строку наиболее эффективно.

Команда find имеет такой синтаксис:

find [ папка] [ параметры] критерий шаблон [действие]

Читайте также:  Уровни громкости микрофона windows 10

Папка — каталог в котором будем искать

Параметры — дополнительные параметры, например, глубина поиска, и т д

Критерий — по какому критерию будем искать: имя, дата создания, права, владелец и т д.

Шаблон — непосредственно значение по которому будем отбирать файлы.

Основные параметры команды find

Я не буду перечислять здесь все параметры, рассмотрим только самые полезные.

  • -P никогда не открывать символические ссылки
  • -L — получает информацию о файлах по символическим ссылкам. Важно для дальнейшей обработки, чтобы обрабатывалась не ссылка, а сам файл.
  • -maxdepth — максимальная глубина поиска по подкаталогам, для поиска только в текущем каталоге установите 1.
  • -depth — искать сначала в текущем каталоге, а потом в подкаталогах
  • -mount искать файлы только в этой файловой системе.
  • -version — показать версию утилиты find
  • -print — выводить полные имена файлов
  • -type f — искать только файлы
  • -type d — поиск папки в Linux

Критерии

Критериев у команды find в Linux очень много, и мы опять же рассмотрим только основные.

  • -name — поиск файлов по имени
  • -perm — поиск файлов в Linux по режиму доступа
  • -user — поиск файлов по владельцу
  • -group — поиск по группе
  • -mtime — поиск по времени модификации файла
  • -atime — поиск файлов по дате последнего чтения
  • -nogroup — поиск файлов, не принадлежащих ни одной группе
  • -nouser — поиск файлов без владельцев
  • -newer — найти файлы новее чем указанный
  • -size — поиск файлов в Linux по их размеру

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

А теперь давайте рассмотрим примеры find, чтобы вы лучше поняли, как использовать эту утилиту.

1. Поиск всех файлов

Показать все файлы в текущей директории:

2. Поиск файлов в определенной папке

Показать все файлы в указанной директории:

Искать файлы по имени в текущей папке:

Не учитывать регистр при поиске по имени:

find . -iname «test*»

3. Ограничение глубины поиска

Поиска файлов по имени в Linux только в этой папке:

find . -maxdepth 1 -name «*.php»

4. Инвертирование шаблона

Найти файлы, которые не соответствуют шаблону:

find . -not -name «test*»

5. Несколько критериев

Поиск командой find в Linux по нескольким критериям, с оператором исключения:

find . -name «test» -not -name «*.php»

Найдет все файлы, начинающиеся на test, но без расширения php. А теперь рассмотрим оператор ИЛИ:

find -name «*.html» -o -name «*.php»

6. Несколько каталогов

Искать в двух каталогах одновременно:

find ./test ./test2 -type f -name «*.c»

7. Поиск скрытых файлов

Найти скрытые файлы:

8. Поиск по разрешениям

Найти файлы с определенной маской прав, например, 0664:

find . type f -perm 0664

Найти файлы с установленным флагом suid/guid:

find / -perm 2644

find / -maxdepth 2 -perm /u=s

Поиск файлов только для чтения:

find /etc -maxdepth 1 -perm /u=r

Найти только исполняемые файлы:

find /bin -maxdepth 2 -perm /a=x

9. Поиск файлов в группах и пользователях

Найти все файлы, принадлежащие пользователю:

find . -user sergiy

Поиск файлов в Linux принадлежащих группе:

find /var/www -group developer

10. Поиск по дате модификации

Поиск файлов по дате в Linux осуществляется с помощью параметра mtime. Найти все файлы модифицированные 50 дней назад:

Поиск файлов в Linux открытых N дней назад:

Найти все файлы, модифицированные между 50 и 100 дней назад:

find / -mtime +50 –mtime -100

Найти файлы измененные в течении часа:

11. Поиск файлов по размеру

Найти все файлы размером 50 мегабайт:

От пятидесяти до ста мегабайт:

find / -size +50M -size -100M

Найти самые маленькие файлы:

find . -type f -exec ls -s <> \; | sort -n -r | head -5

find . -type f -exec ls -s <> \; | sort -n | head -5

12. Поиск пустых файлов и папок

find /tmp -type f -empty

13. Действия с найденными файлами

Для выполнения произвольных команд для найденных файлов используется опция -exec. Например, выполнить ls для получения подробной информации о каждом файле:

find . -exec ls -ld <> \;

Удалить все текстовые файлы в tmp

find /tmp -type f -name «*.txt» -exec rm -f <> \;

Удалить все файлы больше 100 мегабайт:

find /home/bob/dir -type f -name *.log -size +100M -exec rm -f <> \;

Выводы

Вот и подошла к концу эта небольшая статья, в которой была рассмотрена команда find. Как видите, это одна из наиболее важных команд терминала Linux, позволяющая очень легко получить список нужных файлов. Ее желательно знать всем системным администраторам. Если вам нужно искать именно по содержимому файлов, то лучше использовать команду grep.

Источник

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