How to Delete Matching Files in All Subdirectories Using SSH

When managing files on a server via SSH (Secure Shell), it’s common to encounter situations where you need to delete specific files that match a certain pattern. In this article, we’ll explore how to efficiently remove all files with a “.swp” extension in all subdirectories of the current directory using the “find” command in various forms.

Method 1: Using the “-delete” Option

The simplest way to delete matching files is by using the “-delete” option of the “find” command. Execute the following command in the SSH terminal:

find . -name \*.swp -type f -delete

This command instructs “find” to search for files with the “.swp” extension (“-name *.swp”) that are regular files (“-type f”) underneath the current directory (“.”) and directly delete them (“-delete”).

Method 2: Using the “-exec” Option

Another approach is to use the “-exec” option of the “find” command, which allows you to execute an arbitrary command per file. Here are two variants:

find . -name \*.swp -type f -exec rm -f {} \;
find . -name \*.swp -type f -exec rm -f {} +

In the first variant, “{}” represents the placeholder for each matching file, and “\;” denotes the end of the command. This form executes the “rm -f” command individually for each file.

The second variant optimizes the execution by replacing “{}” with as many parameters as possible. This reduces the number of commands executed, making it more efficient when dealing with a large number of files.

Method 3: Using the “xargs” Command

For more complex per-file commands or when dealing with filenames that contain whitespace, you can use the “xargs” command in conjunction with “find”. Here’s an example:

find . -name \*.swp -type f -print0 | xargs -0 rm -f

In this form, the “-print0” option tells “find” to separate matches with ASCII NULL instead of a newline. The “-0” option for “xargs” instructs it to expect NULL-separated input. This ensures that the pipe construct is safe for handling filenames containing whitespace.

Conclusion

Using the “find” command in combination with different options, such as “-delete”, “-exec”, and “xargs”, allows you to efficiently delete matching files in all subdirectories using SSH. Depending on your specific requirements and preferences, you can choose the method that best suits your needs. For more details and examples, consult the manual page of the “find” command (man find) to explore further possibilities.

Reference: Delete matching files in all subdirectories