Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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
1  
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

3 Answers 3

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.

Examples:

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

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) {
unlink($name);
} else {
}
}

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

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

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.