Skip to content

Delete all files EXCEPT the certain pattern


When it comes to managing files in Linux, sometimes we need to delete all files in a directory except for a few specific ones. This can be a bit tricky, especially if we have a large number of files. In this blog post, we will explore how to delete all files except some specific files in Linux.


shopt -s extglob
rm -rf !(*.py|*.tar.gz)


find . -type f ! -name '*.tar.gz' ! -name '*.py' -delete

Back to Table of Contents

  1. License under CC BY-NC 4.0
  2. Copyright issue feedback, replace # with @
  3. Not all the commands and scripts are tested in production environment, use at your own risk
  4. No personal information is collected.