Open In App

How to Delete All Files Before a Certain Date in Linux

Linux, an advanced and open-source operating system, has several file-management commands and utilities. Deleting files in Linux is an essential skill for all users, whether beginner or experienced. In this article, we will learn how to delete all files before a certain date in Linux.

In Linux, you can use the find command with the -exec argument to delete all files created before a specific date.



We will use terminal commands to do all forms of deletion operations, so open your terminal and run all commands carefully to avoid data loss.

How to Delete All Files Before a Certain Date in Linux

Let us find out how to delete all files before a certain date in Linux:



Example 1: Delete all files older than a year:

In this example, we will use the find command to delete all files modified older than 365 days ( 1 year ) in the specified directory, find command helps us to find all files or files with specific extensions within a specified directory. Below is the command to delete all files modified older than 1 year:

find /path/to/your/directory -type f -mtime +365 -exec rm {} \;

here:

In this command you can use the -atime instead of -mtime flag to delete all files that have not been accessed in last 365 days.

find /path/to/your/directory -type f -atime +365 -exec rm {} \;

delete all fies inside gfg directory modified before 1 year

Example 2: Delete files modified within a specific date range:

In this example, we will delete all files modified between a period of time. Let’s say If we want to delete all files modified between 1 january 2023 and 31 decemeber 2023 then we can use the following command:

find /path/to/your/directory -type f -newermt "2023-01-01" ! -newermt "2023-12-31" -exec rm {} \;

here:

Delete all files inside gfg directory modified between 1 jan 2023 and 31 dec 2023

Example 3: Delete all files with specific extension:

In this example, we will select all files with .txt extension and delete the files modified before 365 day or 1 year. here is the command to delete all text files modified before 1 year.

find /path/to/your/directory -type f -name "*.txt" -mtime +365 -exec rm {} \;

Delete all text files inside gfg directory modified before 1 year.

Notes:

Conclusion:

Using the find command in conjunction with these approaches, you can selectively delete files depending on numerous criteria, ensuring a well-organized and optimized file system.

Article Tags :