Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to delete all but 1 file and 1 directory from the directory I am currently in. How do I go about doing this?

I have a directory which has three directories a, b, c and three files 1.php, 2.php, 3.php. I want to remove directories a and b, as well as files 1.php and 2.php only. I am looking for a solution to doing this in an easier manner. I am looking for a solution that could be used on a higher scale with more folders and files.

share|improve this question
Hi all, This is how I solved it using a bash script: #!/bin/bash shopt -s extglob rm -r !(c||3.php) – sniper Jul 26 '11 at 22:03
You can write it as an answer to your own question and mark it as correct. SU relies on questions getting answered that are marked as correct, and this would be the preferred way. – Daniel Andersson Apr 10 '12 at 11:14
find directory -not \( -name temp -o -name 3.php -o -name c -prune \) -delete

A quick test case showed that it worked on this exact case, at least. If there are subdirs named e.g. c or such, I believe you might exclude them as well. It's easy to get it to work in general cases, but to define a find command in all generality takes some testing.

Test without the "-delete" statement to see which files it matches.

PRESSTOP: find changes its behaviour when -delete is specified (find warns about this and won't go on when -prune is specified). You could always pipe output to xargs and rm, or write -execdir rm {} \; instead of -delete, though.


find directory -not \( -name directory -o -name 3.php -o -name c -prune \) -execdir rm -r {} \;
find directory -not \( -name directory -o -name 3.php -o -name c -prune \) -print0 | xargs -0 rm -r

It's always tricky business, and when the goal is to delete files, make extensive test cases. I have quite a few similar finds running nightly, and I can't say I wasn't nervous setting them free :-)

share|improve this answer

My instinct is this - if you have just one file to save and one directory, copy those to a safe place then blow away the rest.

cp /dir/file.txt /safe/dir/
cp -R /dir/to/save /safe/dir/
rm -rf /dir/

share|improve this answer

Try the following script in pseudo perl:

#request the file you don't want to delete and store the name in a scalar variable.

opendir(DIRHANDLE, ".") || die "Could not open Directory handle.";
@list = readdir(DIRHANDLE);

foreach $name (@list) {
if($name != $your_input_variable) {
} else {

share|improve this answer
@mjb Thanks for the markup edit. – Yitzchak Jul 26 '11 at 23:39

You must log in to answer this question.

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