How to clean up files in Linux
Charles
Charles
Linux File Cleanup Commands
Remove Files Older Than 24 Hours
Here are various commands to remove files older than 24 hours:
- Using
find
command with-mtime
:
find /path/to/directory -mtime +1 -type f -delete
- Using
find
with-exec rm
:
find /path/to/directory -mtime +1 -type f -exec rm {} \;
- Using
find
with-ctime
(based on change time):
find /path/to/directory -ctime +1 -type f -delete
- Using
-mmin
for more precise control (1440 minutes = 24 hours):
find /path/to/directory -mmin +1440 -type f -delete
Explanation of parameters:
/path/to/directory
: Replace with your target directory path-mtime +1
: Files modified more than 1 day ago-ctime +1
: Files changed more than 1 day ago-mmin +1440
: Files modified more than 1440 minutes ago-type f
: Only match files (not directories)-delete
: Delete the matched files
Safety tip:
Before deleting, you can remove the -delete
option to see which files would be deleted:
find /path/to/directory -mtime +1 -type f
Count Total Files
Various methods to count files from a find
command:
- Using
wc -l
:
find /path/to/directory -mtime +1 -type f | wc -l
- Using
find
with-printf
andwc
:
find /path/to/directory -mtime +1 -type f -printf '.' | wc -c
- Using a counter variable in combination with
find
:
count=$(find /path/to/directory -mtime +1 -type f | wc -l)
echo "Total files: $count"
- Using
-exec
with a counter:
find /path/to/directory -mtime +1 -type f -exec echo \; | wc -l
Note:
The most common and simplest approach is using wc -l
. Here:
wc -l
counts the number of lines in the output- Each line represents one file found by the
find
command