Bash: Delete All Files Whose Filename Contains String


Often you may want to use Bash to find all files in a particular directory whose filename contains a specific string.

You can use the following syntax to do so:

find . -type f -name '*new*' -delete

This particular example will find all files in the current directory that contain the string “new” in the filename.

Here is what the various commands do:

  • find .: Match all items in current directory
  • -type f: Match only the files
  • -name ‘*new*’: Match only files that contain the string new in the filename
  • -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 Whose Filename Contains Specific String 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_new2024.txt
  • coaches_old2024.txt
  • players_new2024.txt
  • players_old2024.txt

Suppose that we would like to delete all files whose filenames contain the string new somewhere in the name.

We can use the following syntax to do so:

find . -type f -name '*new*' -delete

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

Bash delete all files whose filename contains string

Notice that when we use the ls command again to view the updated contents of the directory we can see that all files whose filename contained the pattern new have been deleted.

Feel free to replace new with any other pattern that you would like.

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