Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I've got a /tmp/test directory. In it I've got a mixture of files and directories. One of those directories is /tmp/test/to_be_kept. Now I'd like to know how do I delete all the files and directories apart from /tmp/test/to_be_kept and everything what's in it? Thanks

share|improve this question
add comment

3 Answers

shopt -s extglob
rm -r /tmp/test/!(to_be_kept)
share|improve this answer
add comment

This will produce some error messages which you can ignore when it tries to re-access directories that have already been removed:

find /tmp/test -mindepth 1 -type d -name to_be_kept -prune -o -exec rm -rf {} \;
share|improve this answer
add comment
  • Here is a simple way:

    ls /tmp/test | grep -v to_be_kept | xargs rm -r
    
  • If you want to delete hidden also:

    ls -a /tmp/test | grep -v to_be_kept | xargs rm -r
    

Always test the output first!

Try these first without the | xargs rm -r part! If you get the list of files and directories you wanted to delete you may as well apply...

share|improve this answer
    
+1 for workable solution complete with "safety first" instructions. –  David Spillett May 22 '10 at 21:23
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.