Linux: Bash Delete All Files In Directory Except Few

You can delete all files in a directory except for a few by using the find command with the -delete option and excluding the desired files with the -not option. Here’s an example:

find /path/to/directory/ -type f ! -name 'file1' ! -name 'file2' -delete

In this example, the find command will search the directory at /path/to/directory/ for files (-type f), and exclude any files named file1 or file2 (! -name 'file1' ! -name 'file2'), before deleting all the files it finds (-delete).

You can add as many ! -name options as needed to exclude additional files.

Leave a Comment