- How to Delete Files Older than 30 days in Linux
- 1. Delete Files older Than 30 Days
- 2. Delete Files with Specific Extension
- 3. Delete Old Directory Recursively
- Conclusion
- linux-notes.org
- Как найти и удалить файлы старше конкретной даты в Linux
- Linux: Delete Files Older Than X Days
- Find files older then
- Explanation
- Delete files older then
- Explanation
- Move files older then
- Explanation
- bash delete file script
- How To Find And Delete Files Older Than X Days In Linux
- Find and delete files older than X days in Linux
- Conclusion
- Linux: использование find для поиска файлов старше
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.
Источник
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: Delete Files Older Than X Days
Posted on June 14, 2013 By Nikola Stojanoski
This is a very simple tutorial on how to find, move and delete files older than X days. I needed this for a project where I collected some images and needed to archive and delete them after a while.
With this, you will be able with the Linux find command to find your JPG files older than 30 days and then execute rm or mv or whatever command you want on them.
Find files older then
Explanation
- First part is the path where your files are located. Don’t use wildcard * if you have a lot of files because you will get Argument list too long error.
- Second part -type is the file type f stands for files
- Third part -name is limiting *,jpg files
- Fourth part -mtime gets how many days the files older then will be listed. +7 is for files older than 7 days.
This is the simple find file command that will list all the .jpg files older than 7 days.
Delete files older then
Explanation
- First part is the path where your files are located. Don’t use wildcard * if you have a lot of files because you will get Argument list too long error.
- Second part -type is the file type f stands for files
- Third part -name is limiting *,jpg files
- Fourth part -mtime gets how many days the files older then will be listed. +15 is for files older than 15 days.
- Fifth part -exec executes a command. In this case rm is the command, <> gets the filelist and \; closes the command
This will delete all the .jpg files older than 15 days.
Move files older then
Explanation
- First part is the path where your files are located. Don’t use wildcard * if you have a lot of files because you will get Argument list too long error.
- Second part -type is the file type f stands for files
- Third part -name is limiting *,jpg files
- Fourth part -mtime gets how many days the files older then will be listed. +30 is for files older than 30 days.
- Fifth part -exec executes a command. In this case mv is the command, <> gets the filelist, path where to move the files and \; closes the command
This will move all the .jpg files older than 30 days into a new directory.
bash delete file script
Now we can combine these two commands to archive the images older than 15 days and delete them from the archive folder if they are older then 30 days.
We are going to create a shell script that will do that and we can run it with a crontab.
This command should work on most of the Linux distributions.
Источник
How To Find And Delete Files Older Than X Days In Linux
It is always recommended to find and cleanup your old files which are no longer necessary after a certain period of time. This will save you some disk space. If you didn’t clean your old files yet, here is a quick way to do that. This brief tutorial walk you through how to find and delete files older than X days in Linux and Unix-like operating systems.
Disclaimer:
You should be extremely careful while running the following commands. These commands will not ask you any confirmation before deleting the files. It will simply delete the files once you hit the ENTER key. So be very careful and double check the files you’re about to delete.
Find and delete files older than X days in Linux
First, let us find out the files older than X days, for example 30 days.
To do, so, just run:
The above command will find and display the older files which are older than 30 day in the current working directorys.
- dot (.) — Represents the current directory.
- -mtime — Represents the file modification time and is used to find files older than 30 days.
- -print — Displays the older files
If you want to search files in a specific directory, just replace the dot with the folder path.
For example, to find out the files which are older than 30 days in /home/sk/Downloads directory, just run:
Sample output:
Find files older than 30 days in Linux
Now, run any one of the following command to delete the files which are not required anymore. Again, I warn you that these commands will delete the files immediately once you hit ENTER button. Please be cautious and double check before running these commands.
Also Read:
Conclusion
Delete old files periodically if they are not necessary at regular intervals, or backup them to any external drives and free up disk space. You can use the free space for any other useful purposes.
Источник
Linux: использование find для поиска файлов старше
find имеет хорошую поддержку для поиска файлов, более измененных менее X дней назад, но как я могу использовать, find чтобы найти все файлы, измененные после определенной даты?
Я не могу найти что-либо на find странице руководства, чтобы сделать это, только для сравнения с временем других файлов или для проверки различий между созданным временем и сейчас. Является ли создание файла с нужным временем и сравнение с этим единственным способом сделать это?
Если у вас есть только «-newer file», вы можете обойти это:
Предполагая, что у вашего касания есть эта опция (у меня сенсорный 5.97).
Нет, вы можете использовать строку даты / времени.
-newerXY reference
Сравнивает временную метку текущего файла со ссылкой. Ссылочным аргументом обычно является имя файла (и для сравнения используется одна из его временных меток), но это также может быть строка, описывающая абсолютное время. X и Y являются заполнителями для других букв, и эти буквы выбирают, какое время относится к тому, как ссылка используется для сравнения.
Не имеет прямого отношения к вопросу, но может быть интересным для тех, кто спотыкается здесь.
Команда find напрямую не поддерживает параметр -older для поиска файлов старше определенной даты, но вы можете использовать оператор отрицания (используя пример принятого ответа):
вернет файлы старше указанной даты.
Источник