Linux find files older 10 days

linux-notes.org

Как найти и удалить файлы старше конкретной даты в Linux

Хочу в этой теме «Как найти и удалить файлы старше конкретной даты в Linux» рассказать как можно найти и удалить определенные файлы по дате в ОС Linux таких как Debian, Ubuntu или Redhat, Centos. На готовых примера покажу что и как нужно делать.

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

пример использование команды ls -lah для вывода подробной информации о файлах

2. Чтобы узнать сегодняшнюю дату, нужно выполнить:

3. Команда что выше не вывела полную дату, можно это исправить:

4. Допустим нужно найти файлы и удалить их по определенной дате.

Если нужно найти все файлы свыше 3 дня и после чего удалить их:

Если нужно найти все файлы свыше 90 дней и после чего удалить их:

Если нужно найти все файлы свыше 365 дней и после чего удалить их:

Если нужно найти все файлы свыше 100 дней и после чего удалить их:

Удаление файлов старше N дней

можно еще вот так:

Ключи:
-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 — количество дней.

Источник

Linux: использование find для поиска файлов старше

find имеет хорошую поддержку для поиска файлов, более измененных менее X дней назад, но как я могу использовать, find чтобы найти все файлы, измененные после определенной даты?

Я не могу найти что-либо на find странице руководства, чтобы сделать это, только для сравнения с временем других файлов или для проверки различий между созданным временем и сейчас. Является ли создание файла с нужным временем и сравнение с этим единственным способом сделать это?

Читайте также:  Пиктограмма windows что это

Если у вас есть только «-newer file», вы можете обойти это:

Предполагая, что у вашего касания есть эта опция (у меня сенсорный 5.97).

Нет, вы можете использовать строку даты / времени.

-newerXY reference
Сравнивает временную метку текущего файла со ссылкой. Ссылочным аргументом обычно является имя файла (и для сравнения используется одна из его временных меток), но это также может быть строка, описывающая абсолютное время. X и Y являются заполнителями для других букв, и эти буквы выбирают, какое время относится к тому, как ссылка используется для сравнения.

Не имеет прямого отношения к вопросу, но может быть интересным для тех, кто спотыкается здесь.

Команда find напрямую не поддерживает параметр -older для поиска файлов старше определенной даты, но вы можете использовать оператор отрицания (используя пример принятого ответа):

вернет файлы старше указанной даты.

Источник

How to Delete Files Older than 30 days in Linux

This is the best practice to remove old unused files from your server. For example, if we are running daily/hourly backup of files or database on the server then there will be much junk created on the server. So clean it regularly. To do it you can find older files from the backup directory and clean them.

This article describe you to how to find and delete files older than 30 days. Here 30 days older means the last modification date is before 30 days.

1. Delete Files older Than 30 Days

You can use the find command to search all files modified older than X days. And also delete them if required in single command.

First of all, list all files older than 30 days under /opt/backup directory.

Verify the file list and make sure no useful file is listed in above command. Once confirmed, you are good to go to delete those files with following command.

2. Delete Files with Specific Extension

Instead of deleting all files, you can also add more filters to find command. For example, you only need to delete files with “.log” extension and modified before 30 days.

For the safe side, first do a dry run and list files matching the criteria.

Once the list is verified, delete those file by running the following command:

Above command will delete only files having .log extension and last modification date is older than 30 days.

3. Delete Old Directory Recursively

Using the -delete option may fail, if the directory is not empty. In that case we will use Linux rm command with find command.

The below command will search all directories modified before 90 days under the /var/log directory.

Here we can execute the rm command using -exec command line option. Find command output will be send to rm command as input.

Conclusion

In this tutorial, you have learned to search and delete files modified older than specific days in Linux command line.

Источник

How to Delete files older than 30 Days in Linux

It is a best practice to find and remove old or unused files from the Linux system after a certain period of time, as this will free up some space on the system, which can be used for some other purpose.

Читайте также:  Linux home directory path

Please make sure these files are no longer needed, as it will not ask for your confirmation before deleting the files.

Are you wondering how to delete older files in your Linux system? This quick guide show you how to find and remove files older than 30 days in Linux.

To delete files older than 30 days on your Linux server, you need to use multiple commands together such as find command, ‘mtime’ command, ‘exec’ command and rm command.

What’s mtime command

mtime (File Last Modify Time) – mtime shows when you modify, append or update a file content. The time argument consider an input value as ’24 hours’. For example, time 2 = 2*24 hours (2 days).

1) Search and Delete files older than 30 days

First, we will find out all files older than 30 days under the ‘/home/linuxgeek/Downloads’ directory.

The below output will allow you to check whether these files are needed before they are deleted. If not, delete them using the below command.

Once you have decided that these files are no more requires then go ahead and delete it, using one of the following command.

Details:

  • find: find is a command
  • /home/linuxgeek/Downloads: Path to files (It should be replaced by yours)
  • -type f: What Type of files
  • -mtime +30: It filters 30 days old files.
  • -exec rm -f Perform a file remove action
  • <>: Represents the file found by Find command.
  • \; It will end the command.

2) Delete files older than ‘X’ days with Wildcard option

In many cases, you may have to delete files based on the name when there are many log files with different names in the log directory, I usually use this command to delete files older than 30 days on the system.

It is always recommended to do a dry run instead of removing directly. This will give you the time to check before deleting the files.

Once you verified the list, select one of the following commands to remove it.

3) Delete files older than 10 days with Specific Extension

Sometimes you may need to delete files based on file extension instead of deleting them. For instance, to delete files with “.log” extension and modified within 10 days, run:

First, let’s find and print a list of log files older than 10 days under the ‘/var/log’ directory:

Check the list and delete it using one of the following command if it is no longer needed.

Final Thoughts

In this guide, we’ve shown you how to delete files older than 30 days on Linux with three different examples. It is not limited to 30 days and days can be changed as needed like 10 days or 90 days or even 120 days.

If you have any questions or feedback, feel free to comment below.

Источник

How To Delete Files Older Or Newer Than N Days Using find (With Extra Examples)

This article explains how to delete files older or newer than N days, with extra examples like matching only files using a particular extension, and more. For this we’ll use find , a command line tool to search for files in a directory.

You can delete all files and folders older than (with the file’s data modification time older than) N days from a directory by using:

Читайте также:  Сборка windows 10 1607 обновление

An explanation of the whole command and what you need to replace:

  • find is the Unix command line tool for finding files (and more)
  • /directory/path/ is the directory path where to find (and delete) files. Replace it with the path of the directory from which you want to delete files and folders older than N days
  • -mindepth 1 is used to not apply any tests or actions at levels less than the specified level. -mindepth 1 means the command should process all files except the command line arguments. Without using this, the command would attempt to also remove /directory/path/ if it matches the find criteria. You can skip it in all the commands mentioned in this article if you want to also match the specified find path. Also, there’s no need to specify this if you only look for files ( -type f for regular files for example), and not folders
  • -mtime +N is used match files that had their data (content) last modified N days ago. Replace N with a number (integer). In this command, files with a modification time older than N days will be deleted. It’s important to note that for example, if a file was last modified 1 day and 23 hours ago, -mtime +1 won’t match it, treating it as if the file was last modified 1 day, 0 hours, 0 minutes, and 0 seconds ago; see this explanation on why that’s the case, since the find man page doesn’t do this very well
  • -delete deletes matched files and folders

It’s important to note that -delete is a GNU extension, so it’s not available in all find implementations. For other ways of deleting files that works with all implementations, read the observations further down this article.

Want to test the command without removing any files or folders? Remove -delete and the command will list all files it finds matching your criteria, without deleting them:

Let’s take a look at an example. To delete all files and folders older than 10 days from the

/Downloads folder you can use:

To delete all files and folders newer than (with a file modification time newer than) N days, use -N instead of +N :

Example in which we’ll remove all files and folders from

/Downloads that had their contents modified between now and 10 days ago:

A few important observations that I recommend reading:

Other examples of using find to delete files or folders based on their modification time

Only delete regular files older than N days, keeping empty subdirectories:

Here we’ve used -type f to match only regular files. You can also use -type d to match folders, or -type l to match symbolic links.

Only delete files matching .extension older than N days from a directory and all its subdirectories:

You can add -maxdepth 1 to prevent the command from going through subdirectories, and only delete files and 1st level depth only directories:

You may also use -ctime +N , used to match (and delete in this example) files that had their status last changed N days ago (the file attributes/metadata AND/OR file content was modified), as opposed to -mtime , which only matches files based on when their content was last modified:

Источник

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