When managing files in Ubuntu or macOS, you may need to delete everything in a directory except certain file types, such as images or important HTML files. Using the find
command, you can efficiently remove unwanted files while preserving the ones you need.
This guide will show you how to delete all files in the current directory while keeping specific file types like .jpg
, .jpeg
, .png
, and index.html
intact.
Deleting All Files Except .jpg Files in Ubuntu
To delete all files in the current folder except .jpg
files, use:
find . -maxdepth 1 -type f ! -name "*.jpg" -delete
Explanation:
-
find .
→ Search in the current directory. -
-maxdepth 1
→ Restrict search to only the current folder (ignore subdirectories). -
-type f
→ Only target files (ignore directories). -
! -name "*.jpg"
→ Exclude.jpg
files. -
-delete
→ Delete all other files.
⚠ Warning: This action is irreversible. To preview the files before deleting, run:
find . -maxdepth 1 -type f ! -name "*.jpg"
Keeping Multiple File Types (JPG, JPEG, PNG, and index.html)
If you want to delete all files except .jpg
, .jpeg
, .png
, and index.html
, use:
find . -maxdepth 1 -type f ! -iname "*.jpg" ! -iname "*.jpeg" ! -iname "*.png" ! -name "index.html" -delete
Additional Options:
-
! -iname "*.jpg"
→ Keep.jpg
and.JPG
(case-insensitive). -
! -iname "*.jpeg"
→ Keep.jpeg
and.JPEG
. -
! -iname "*.png"
→ Keep.png
and.PNG
. -
! -name "index.html"
→ Keepindex.html
(case-sensitive).
To preview the files before deletion, run:
find . -maxdepth 1 -type f ! -iname "*.jpg" ! -iname "*.jpeg" ! -iname "*.png" ! -name "index.html"
Deleting Files on macOS
The find
command in macOS works the same way as in Ubuntu. You can safely use the same command:
find . -maxdepth 1 -type f ! -iname "*.jpg" ! -iname "*.jpeg" ! -iname "*.png" ! -name "index.html" -delete
Alternative: Move Instead of Delete
If you want to move the unwanted files to another folder instead of deleting them immediately, use:
mkdir unwanted_files
find . -maxdepth 1 -type f ! -iname "*.jpg" ! -iname "*.jpeg" ! -iname "*.png" ! -name "index.html" -exec mv {} unwanted_files/ \;
This moves all unwanted files to the unwanted_files
directory for later review.
Final Thoughts
Using find
with -delete
is a powerful way to manage files in Ubuntu and macOS. However, always preview the files before deletion to avoid losing important data. If unsure, consider moving files instead of deleting them permanently.
By using these commands carefully, you can keep your directories clean while ensuring your essential files remain untouched.
Leave a Reply