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

(Mike) #1

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?

(Bibin Wilson) #2

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 {} +

(gskr.scm) #3

Below command also can be used:

ls | grep -v file.txt | xargs rm

(Bibin Wilson) #4

@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

(Annmary) #5

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