Bash: How to Delete All Files Except Specific One


Often you may want to use Bash to delete all files in a particular directory except for specific ones.

You can use the following syntax to do so:

find . -type f ! -name 'players.txt' -delete

This particular example will delete all files in the current directory except for the file named players.txt.

Here is what the various commands do:

  • find .: Match all items in current directory
  • -type f: Match only the files
  • ! -name ‘players.txt’: Match only files that do not have the name players.txt
  • -delete: Delete each of the matched files

Note that you can also replace find . with find /some/directory/path to match all files in a specific directory.

The following example shows how to use this syntax in practice.

Example: How to Delete All Files Except Specific Ones in Bash

Suppose that our current directory is located at the following path:

  • c:/users/bobbi/data2

We can use the ls command to first view all items in this directory:

We can see that this directory contains the following files:

  • coaches.txt
  • managers.txt
  • owners.txt
  • players.txt

Suppose that we would like to delete all files in this current directory except for the file named players.txt.

We can use the following syntax to do so:

find . -type f ! -name 'players.txt' -delete

The following screenshot shows how to use this syntax in practice:

Bash delete all files except

Notice that when we use the ls command again to view the updated contents of the directory we can see that all files in the directory except the file named players.txt have been deleted.

Feel free to replace players.txt with your own specific filename that you don’t want to delete.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Find All Files that Start with Specific Pattern
Bash: How to Find All Files that End with Number
Bash: How to Find All Files that Were Created Today

Leave a Reply