Skip to content

How to delete specific files EXCEPT the certain pattern



Working with files in Linux can be a tricky task, especially when it comes to deleting them. There might be situations where you need to delete all files in a directory except for those that match a certain pattern. This can be a tedious and time-consuming task if done manually. Fortunately, there is a simple solution in Linux that can help you accomplish this task quickly and efficiently.

When it comes to managing files, sometimes we need to delete a lot of files at once. However, what if we want to delete all files, except for a certain pattern? This can be a bit tricky to accomplish, but with the right method, it can be done quickly and efficiently. In this article, we will explain how to delete all files except for a certain pattern.

Using rm

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

Using find

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

  • Welcome to visit the knowledge base of SRE and DevOps!
  • License under CC BY-NC 4.0
  • Made with Material for MkDocs and improve writing by generative AI tools
  • Copyright issue feedback, replace # with @