1 Replies - 503 Views - Last Post: 19 January 2012 - 09:22 AM Rate Topic: -----

Topic Sponsor:

#1 Zel2008  Icon User is offline

  • D.I.C Addict

Reputation: 11
  • View blog
  • Posts: 593
  • Joined: 06-January 09

Clearing a directory except for three specific files

Posted 17 January 2012 - 06:29 AM

Hi all,
I have a directory that needs to be periodically cleared (so this isn't a one-time thing), but when this directory needs to be cleared, one folder and two files have to be kept. The list of files that need to be kept is:

CVS/
config
script

The CVS directory, for those who aren't familiar with the CVS version control system, is there in development, but it isn't there when we distribute our software, so the command that cleans the directory needs to be able to work whether or not the CVS directory is there. At the moment, I have this clunky script that handles the deletion:

mv config .config
mv script .script
mv CVS .TempCVS
rm -rf *
mv .config config
mv .script script
mv .TempCVS CVS



Basically, it hides all the files I want to keep, deletes all the rest, then makes the hidden files visible again. The problem is that it doesn't work if the CVS directory isn't there to begin with -- it says there's no such directory.

I'm trying to figure out a way to make this as simple as possible, both for myself and for the users of our open-source software -- I don't have globs enabled on my computer, for example, so it can't be done that way.

Does anyone know of a quick and easy way this can be done? I've Googled for over a day with no success, and I have a feeling I'm missing something small and silly.

Thanks,
Zel2008

EDIT: Never mind, I finally got it. It turns out things have to be done in two steps -- delete files first, saving those you want, then delete directories, saving those you want. So, for my previous example, if it was in a directory called myDir, the proper commands would be:

find myDir -maxdepth 1 -type f ! -name config ! -name script -delete
find myDir -type d ! -name myDir ! -name CVS -exec rm -rf '{}' \;



You can add as many more directories or files as you want. :)

This post has been edited by Zel2008: 17 January 2012 - 07:36 AM


Is This A Good Question/Topic? 0
  • +

Replies To: Clearing a directory except for three specific files

#2 Gorian  Icon User is offline

  • ninja DIC
  • member icon


Reputation: 79
  • View blog
  • Posts: 1,546
  • Joined: 28-June 08

Re: Clearing a directory except for three specific files

Posted 19 January 2012 - 09:22 AM

an alternative possibly:

for i in `find $dir | grep -ve 'file1' -e 'file2'`;do
    rm -r $i;
done;



the -v says everything that doesn't match the pattern for grep. Then deleting everything else.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1