[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: scripting question



[Please wrap your mails at something under 80 columns. I find 72 is a
good choice.]

On Tue, Apr 15, 2003 at 05:18:50PM -0700, Maria Rodriguez wrote:
> I've got a scripting question for you bash lovers out there.
> 
> I have a directory that has a lot of subdirectories, only one of which
> I want to keep.  Let's say I want to keep only the "B" subdirectory
> below:
> 
> /path/to/A
> /path/to/B
> /path/to/C
> 
> Is there a way >>> on the command line <<< to remove all the
> directories other than B?  I thought there might be a way to do this
> with "find" but nothing I've tried yet seems to work.

If you don't mind being bash-specific, then:

  shopt -s extglob  # this can go in your .bashrc if you like
  rm -rf /path/to/!(B)

You can put multiple patterns inside "!(...)", separated by "|". See the
"Pattern Matching" subsection in the bash(1) man page.

If you want something that works in any POSIX shell, you could also use
find, as follows:

  find /path/to -maxdepth 1 -name B -o -type d -print0 | xargs -0 rm -rf

You can add extra patterns by adding more "-name whatever -o" fragments
after the first one above.

With both of these, I advise using 'echo' at first in place of 'rm -rf',
just to be sure.

Cheers,

-- 
Colin Watson                                  [cjwatson@flatline.org.uk]



Reply to: