How to delete all but one file in Unix?

ls * | grep -v dont_delete_this_file | xargs rm -rf 

Example :

mkdir test && cd test
touch test1
touch test2
touch test3
touch test4
touch test5

To remove all files except 'test2' :

ls * | grep -v test2 | xargs rm -rf

Then 'ls' output is :

test2

EDIT:

Thanks for the comment. If the directory contains some files with spaces :

mkdir test && cd test
touch "test 1"
touch "test 2"
touch "test 3"
touch "test 4"
touch "test 5"

You can use (with bash) :

rm !("test 1"|"test 4")

'ls' output :

test 1
test 4

Assuming you're using the bash shell (the most common case), you can use the negation globbing (pathname expansion) symbol:

rm -rf !(myfile.txt)

This uses extended globbing, so you would need to enable this first:

shopt -s extglob

Tags:

Unix

Rm