• Earn real money by being active: Hello Guest, earn real money by simply being active on the forum — post quality content, get reactions, and help the community. Once you reach the minimum credit amount, you’ll be able to withdraw your balance directly. Learn how it works.

Linux 🧹 How to delete all files in a Linux directory except for the necessary extensions

dEEpEst

☣☣ In The Depths ☣☣
Staff member
Administrator
Super Moderator
Hacker
Specter
Crawler
Shadow
Joined
Mar 29, 2018
Messages
13,861
Solutions
4
Reputation
32
Reaction score
45,552
Points
1,813
Credits
55,350
‎7 Years of Service‎
 
56%
🧹 How to delete all files in a Linux directory except for the necessary extensions

Want to empty a folder, but keep .zip, .txt or .odt? There are three ways to do this in Linux:

🔧 1. Extended Bash patterns (`extglob`)
Bash:
shopt -s extglob
rm -v !(*.zip|*.odt)
shopt -u extglob
Deletes all files except .zip and .odt. Convenient for quick deletion in one folder.

🔍 2. Via `find` - powerful and recursive
Bash:
find . -type f -not -name "*.gz" -delete
Deletes everything except .gz. Good for nested directories and complex filters.

⚙️ 3. Bash variable `GLOBIGNORE`
Bash:
GLOBIGNORE=*.odt:*.txt
rm -v *
unset GLOBIGNORE
Removes everything except the specified extensions. Convenient if you are in Bash and want to quickly exclude what you need.
 
Back
Top