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.

How can I remove all files in one folder minus one file (.zip) from the command line? I am using bash to ssh to my server where I want to do this. I know I could use rm -rf * being in that folder, but I need to keep the zipped file as that contains all the new files to replace the others. How can I do this from the command-line?

share|improve this question
add comment

2 Answers

up vote 3 down vote accepted
$ shopt -s extglob
$ rm -fr !(*.zip)

info "(bash) Pattern Matching"

   If the extglob shell option is enabled using the shopt builtin, several extended pattern matching  opera‐
   tors are recognized.  In the following description, a pattern-list is a list of one or more patterns sep‐
   arated by a |.  Composite patterns may be formed using one or more of the following sub-patterns:

          ?(pattern-list)
                 Matches zero or one occurrence of the given patterns
          *(pattern-list)
                 Matches zero or more occurrences of the given patterns
          +(pattern-list)
                 Matches one or more occurrences of the given patterns
          @(pattern-list)
                 Matches one of the given patterns
          !(pattern-list)
                 Matches anything except one of the given patterns
share|improve this answer
1  
I cannot find a manual entry for shopt. $ man shopt No manual entry for shopt So I guess I do not have it on my OSX using Bash. –  rhand Aug 18 '12 at 5:13
    
The OS can be a pretty important tag as the shell varies so much. I retagged your question for you, but try to be as specific as possible. –  Aaron Copley Aug 18 '12 at 5:16
    
Never mind. Found it in man bash. Will see if it works on the server though. Not sure I can work with this a Dreamhost. They run Debian and Bash. PS Will add the OS tag the next time, but as I will try this a the hoster which runs Debian as well I should perhaps use Debian or Linux as tag –  rhand Aug 18 '12 at 5:18
    
Sheesh... Make up your mind. :) –  Aaron Copley Aug 18 '12 at 5:21
1  
My answer above would work on Mac OS X. –  Aaron Copley Aug 18 '12 at 5:32
show 1 more comment

find . ! -name 'file.zip' -delete

man find

share|improve this answer
    
This will also remove any subfolders and their contents. –  Ignacio Vazquez-Abrams Aug 18 '12 at 5:13
    
Ok, I assumed based on the -r option to rm that this would be desired, but he could find . -maxdepth 1 -type f ! -name 'file.zip' -delete. A good reason to sanity check any answer before copy/pasting into their shell. :) –  Aaron Copley Aug 18 '12 at 5:16
add comment

Your Answer

 
discard

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

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