13

Possible Duplicate:
How to delete all files in a directory except some?

How to delete all but one(or some) file in Unix?

Something like

 rm -rf -ignore myfile.txt *
djsmiley2kStaysInside
  • 6,943
  • 2
  • 36
  • 48
Jean
  • 297

6 Answers6

20
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
8

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
Lauren
  • 181
1
 cp myfile.txt somewhere_else;
 rm -rf *
 cp somewhere_else/myfile.txt .
Rayfleck
  • 111
1
ln myfile.txt .myfile.txt && rm -rf * && mv .myfile.txt myfile.txt
jlliagre
  • 14,369
0

This page gives a variety of options depending on the shell: http://www.unix.com/unix-dummies-questions-answers/51400-how-remove-all-except-one-file.html

0

For a recursive rm you'd need to do the recursion with find and exclude the file(s) you wanted to keep (or grep, but that can get you into whitespace trouble). For a shell glob, modern shells have glob patterns that can be used to exclude files; this can be combined with shell-level glob recursion when available (e.g. zsh has rm **/*~foo/bar — note that this is likely to run into argument length limits for large directory trees).

geekosaur
  • 12,091