Is your Linux system cluttered with excessive files? This guide demonstrates how to efficiently locate and remove files exceeding or falling short of a specified size, reclaiming valuable disk space. We'll leverage the powerful find
command for this task.
Caution: File deletion is permanent. Always back up your data before proceeding.
Table of Contents
Listing Files by Size
Before deleting, it's crucial to preview the files targeted for removal. The -print
option with the find
command provides this preview without actually deleting anything.
To list .doc
files under 5MB in the current directory:
find . -type f -name "*.doc" -size -5M -print
Command Breakdown:
find .
: Searches the current directory and its subdirectories.-type f
: Limits the search to regular files.-name "*.doc"
: Filters for files ending in .doc
.-size -5M
: Selects files smaller than 5 Megabytes.-print
: Displays matching files.Replace .
with a specific path to search other directories. To list files larger than 5MB, use 5M
instead of -5M
.
The -size
operator uses -
for "less than" and
for "greater than." Units include G (Gigabytes), M (Megabytes), K (Kilobytes), and c (bytes).
Examples:
find . -type f -size -10k
find . -type f -size 2G
find . -type f -size 500c
Deleting Files Based on Size
After verifying the file list, replace -print
with -delete
to perform the actual deletion.
Critical Note: -delete
is irreversible. Always double-check your command and directory path. Consider testing on a sample directory first.
Removing Files Smaller Than X Size
To delete .doc
files smaller than 5MB:
find . -type f -name "*.doc" -size -5M -delete
Removing Files Larger Than X Size
To delete .doc
files larger than 5MB:
find . -type f -name "*.doc" -size 5M -delete
Alternative Deletion Commands
The -exec rm {} \;
construct offers an alternative:
find . -type f -name "*.doc" -size -5M -exec rm {} \;
This executes rm
(remove) on each found file. Use 5M
for larger files.
Interactive Deletion Confirmation
For enhanced safety, add -i
to rm
:
find . -type f -name "*.doc" -size -5M -exec rm -i {} \;
This prompts for confirmation before deleting each file.
Best Practices
-print
before -delete
.-size
precisely.-delete
is permanent.Conclusion
Linux offers robust tools for managing files by size. The find
command, combined with -delete
or rm
, provides powerful yet potentially destructive capabilities. Always prioritize data backup and careful command execution. Interactive confirmation (rm -i
) is highly recommended for added safety.
The above is the detailed content of How To Delete Files Bigger Or Smaller Than X Size In Linux. For more information, please follow other related articles on the PHP Chinese website!