Linux find delete old files

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: 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.

Читайте также:  Советы для windows nvidia

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.

Источник

Find And Delete Oldest File If There Are More Than X Files In A Directory In Linux

I have many movies in my hard drive and I have stored them in different folders based on the movie genre. Now, I want to keep only particular number of movie files in a directory, and delete everything else. More importantly, I want to delete only the oldest files. This way I can maintain a constant number of files in each folder. Since I have so many files scattered across many folders, it is quite time consuming process to go to each folder, search for the oldest files and manually delete them one by one. While looking for an easy way to do this, I found the following solution. Read on. It’s not that difficult.

Find and delete oldest file in a directory in Linux

Let us say, you wanted to find and delete the oldest file if there are more than 10 files in a directory. How would you do? It’s very simple.

Take the following directory named ostechnix as an example. Let us check how many files are in this directory using command:

Or cd into that directory and run:

Sample output:

As you see in the above example, the directory ostechnix contains 33 files. I don’t want 33 files in this directory. I want to delete all oldest files and keep only 10 files.

Читайте также:  Uport 1150 драйвер windows 10 64 bit

Now, let us find and delete oldest file(s) in this directory if it contains more than 10 files. To do so, go to that directory:

And, run the following command:

  • ls : List directory contents.
  • -1t : 1(Number one) indicates that the output of ls should be one file per line. t indicates sort contents by modification time, newest first.
  • tail : Output the last part of files.
  • -n +11 : output the last NUM lines, instead of the last 10; or use -n +NUM to output starting with line NUM
  • xargs : Build and execute command lines from standard input.
  • rm -f : Remove files or directories. f indicates ignore nonexistent files and arguments, never prompt. It means that this command won’t display any error messages if there are less than 10 files.
  • | — It is a pipeline. It is generally a sequence of one or more commands separated by one of the control operators | or |& .

So, the above command will delete the oldest files if there are more than 10 files in the current working directory. To verify how many files are in the directory after deleting the oldest file(s), just run:

Update:

If the filenames contains spaces, the above command will not work. Because, the xargs command takes white space characters (tabs, spaces, new lines) as delimiters. In that case, you can narrow it down only for the new line characters ( ‘\n’ ) with -d option like below:

Источник

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

Очень важно находить и очищать старые файлы, которые больше не нужны через определенный промежуток времени.

Вот быстрый способ сделать это.

В этом кратком руководстве вы узнаете, как находить и удалять файлы старше X дней в Linux и Unix-подобных операционных системах.

Найти и удалить файлы старше X дней в Linux

Отказ от ответственности: вы должны быть очень осторожны при выполнении этих команд.

Эти команды не запрашивают подтверждения перед удалением файлов.

Он просто удалит файлы после нажатия клавиши ENTER. Так что будьте очень осторожны!

Сначала давайте узнаем файлы старше X дней, например 30 дней.

Чтобы сделать так, просто:

Вышеупомянутая команда найдет и отобразит старые файлы старше 30 дней. Вот,

dot (.) – Представляет текущий каталог.
-mtime – представляет время изменения файла и используется для поиска файлов старше 30 дней.
-print – отображает старые файлы

Если вы хотите искать файлы в определенном каталоге, просто замените точку на путь папки.

Например, чтобы узнать файлы, которые старше 30 дней в каталоге / home / sk / Downloads, просто запустите:

Теперь, чтобы удалить файлы, запустите любую из следующих команд.

Снова предупреждаю вас, что эти команды будут удалять файлы сразу после нажатия кнопки ENTER.

Перед выполнением этих команд будьте осторожны и дважды проверьте их.

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

Вы можете использовать свободное пространство для любых других полезных целей.

Источник

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