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 *
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 :



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
  • Was going to do very similar using find, but yours works and you were faster. +1
    – Rory Alsop
    Mar 30 '11 at 18:06
  • 2
    this fails if you have files with spaces in their names.
    – Mat
    Mar 30 '11 at 18:08
  • To handle filenames with spaces one could use ls -1 | grep -v do_not_delete | xargs -I files rm "files"
    – sebhofer
    Apr 1 '13 at 12:42

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
 cp myfile.txt somewhere_else;
 rm -rf *
 cp somewhere_else/myfile.txt .
ln myfile.txt .myfile.txt && rm -rf * && mv .myfile.txt myfile.txt

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


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).

Not the answer you're looking for? Browse other questions tagged or ask your own question.