Understanding the Find Command
Learn how to efficiently search and manage files with the find
command. This post covers essential examples for finding, deleting, and compressing files based on various criteria like name, size, and modification time.
Generalized Syntax for find Command:
find [path] [conditions] [actions]
- [path]: Directory to start the search (e.g., . for current directory, /path/to/directory for a specific path).
- [conditions]: Criteria to filter files (e.g., -name “*.log” for files with a specific name, -mtime +7 for files older than 7 days).
- [actions]: What to do with the found files (e.g., -exec rm {} \; to delete files, -exec gzip {} \; to compress files).
Example Commands:
# 1. Delete .trc files older than 1 day
find . -name "*.trc" -type f -mtime +1 -exec rm {} \;
# 2. Compress .log files older than 10 days
find . -name "*.log" -type f -mtime +10 -exec gzip {} \;
# 3. Delete empty files (size 0)
find . -type f -size 0 -exec rm {} \;
# 4. Compress files larger than 10MB
find . -type f -size +10M -exec gzip {} \;
# 5. Find files modified in the last 5 days
find . -type f -mtime -5 -print
# 6. Delete .arc files older than 30 days in a specific directory
find /path/to/directory -name "*.arc" -type f -mtime +30 -exec rm {} \;
# 7. Find and print the 5 largest files modified in the last day
find . -type f -mtime -1 -printf "%p %s\n" | sort -k2nr | head -5
# 8. Delete all .gz files older than 7 days
find . -name "*.gz" -type f -mtime +7 -exec rm {} \;
# 9. Compress .trm files older than 0 days (immediate compression)
find . -name "*.trm" -type f -mtime +0 -exec gzip {} \;
# 10. Delete files larger than 100MB
find . -type f -size +100M -exec rm {} \;
This provides a concise overview of the find
command with examples for common use cases, including deleting, compressing, and filtering files based on different criteria.