Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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 *
share|improve this question

migrated from stackoverflow.com Mar 30 '11 at 18:28

This question came from our site for professional and enthusiast programmers.

marked as duplicate by slhck Jan 11 '13 at 23:17

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

6 Answers 6

up vote 19 down vote accepted
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
share|improve this answer
    
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

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

share|improve this answer

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

share|improve this answer
 cp myfile.txt somewhere_else;
 rm -rf *
 cp somewhere_else/myfile.txt .
share|improve this answer

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
share|improve this answer
ln myfile.txt .myfile.txt && rm -rf * && mv .myfile.txt myfile.txt
share|improve this answer

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