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

Something like

 rm -rf -ignore myfile.txt *
link|improve this question
This belongs on superuser. Voting to move. – Ken White Mar 30 '11 at 18:09
feedback

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

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

6 Answers

up vote 8 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
link|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
1  
this fails if you have files with spaces in their names. – Mat Mar 30 '11 at 18:08
feedback
 cp myfile.txt somewhere_else;
 rm -rf *
 cp somewhere_else/myfile.txt .
link|improve this answer
feedback

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

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

link|improve this answer
feedback

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

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

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