Have you ever needed to clean up a project directory but didn’t want to lose your hidden files or the all-important README.md?
Let’s talk about a simple, safe, and powerful command-line trick to do just that — using find
.
🧩 The Problem
Say you’ve built and compiled several binaries, created temporary files, or generated test outputs. You want to wipe everything except:
- Hidden files (e.g., .git, .env, .gitignore)
- README.md
But using something like rm *
will delete almost everything — and it won’t touch hidden files, which can be misleading. You need a smarter, safer approach.
✅ The Solution
find . -maxdepth 1 ! -name '.*' ! -name 'README.md' ! -name '.' -exec rm -rf {} +
🔍 Breakdown:
-
find . -maxdepth 1
: Only search in the current directory (not recursively). -
! -name '.*'
: Don’t touch hidden files/directories. -
! -name 'README.md'
: Keep your documentation safe. -
! -name '.'
: Prevent deleting the current directory. -
-exec rm -rf {} +
: Delete everything else — files and folders.
Before:
$ ls -al
calculator calculator.c func func.c hello hello.c ...
.git .gitignore README.md
After:
$ find . -maxdepth 1 ! -name '.*' ! -name 'README.md' ! -name '.' -exec rm -rf {} +
$ ls -al
.git .gitignore README.md
🛡️ Safety Tip
Before running rm -rf, test the output with:
find . -maxdepth 1 ! -name '.*' ! -name 'README.md' ! -name '.' -exec echo {} +
This prints the files that would be deleted.
Finally run:
find . -maxdepth 1 ! -name '.*' ! -name 'README.md' ! -name '.' -exec rm -rf {} +
Top comments (0)