1

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?

2 Answers 2

3
$ 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
6
  • 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, 2012 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. Aug 18, 2012 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, 2012 at 5:18
  • Sheesh... Make up your mind. :) Aug 18, 2012 at 5:21
  • 1
    My answer above would work on Mac OS X. Aug 18, 2012 at 5:32
1

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

man find

2
  • This will also remove any subfolders and their contents. Aug 18, 2012 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. :) Aug 18, 2012 at 5:16

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .