How to delete all files/directories with exception/s using RM command in Linux

You can delete all files and/or directories with some exceptions using this command:

[root@testserver temp]#ls  | grep -v "<name>\|<name>" | xargs rm -rf

ls command to list all the names of files and folders on our current directory.

grep -v (grep inverse) to filter all the names of files and folders which are not on your <name> list.

xargs to pass the results from the previous commands as input to rm -rf command which we will be using to delete the files/folders.

I’ll be using these set of files for my demo:

[root@testserver /tmp]# ls
dir1 dir2 dir3 file1.txt file2.txt file3.txt
[root@testserver /tmp]#

I will use the command above to delete all files and directories except for file1.txt and dir2.

[root@testserver /tmp]# ls | grep -v "file1.txt\|dir2" | xargs rm -rf

Here’s the result:

[root@testserver /tmp]# ls
dir2 file1.txt
[root@testserver /tmp]#

Now, all files except for file1.txt and dir2 have been deleted.