How to delete all files in a directory except one in Linux?

I am using a Redhat 7 server and I have many files in a directory. I want to delete all the files except one file. How can i achieve this?

To delete all the regular file types use

find . ! -name 'your-file.txt' -type f -exec rm -f {} +

The above command will find the file that should not be deleted and deletes all the other file using rf -f command.

If your directory has regular files and directories you should use the -type add d and use rm -rf as shown below.

find . ! -name 'your-file.txt' -type d -exec rm -rf {} +

Below command also can be used:

ls | grep -v file.txt | xargs rm

1 Like

@gskr.scm Just to add to your command, if you have both flat files and directories, the following file will help

ls | grep -v file.txt | xargs rm -rf
1 Like

Another take in a different direction (if there are no spaces in file names)

ls | grep -v file.txt | xargs rm
or (works even if there are spaces in file names)

ls | grep -v file.txt | parallel rm
from man grep:

-v, --invert-match
Invert the sense of matching, to select non-matching lines. (-v is specified by Pc