glen
glen

Reputation: 5

Delete all files except

I have a folder with a few files in it; I like to keep my folder clean of any stray files that can end up in it. Such stray files may include automatically generated backup files or log files, but could be a simple as someone accidentally saving to the wrong folder (my folder).

Rather then have to pick through all this all the time I would like to know if I can create a batch file that only keeps a number of specified files (by name and location) but deletes anything not on the "list".

Upvotes: 0

Views: 284

Answers (2)

Matteo
Matteo

Reputation: 14940

[edit] Sorry when I first saw the question I read bash instead of batch. I don't delete the not so useful answer since as was pointed out in the comments it could be done with cygwin.

You can list the files, exclude the one you want to keep with grep and the submit them to rm.

If all the files are in one directory:

ls | grep -v -f ~/.list_of_files_to_exclude | xargs rm

or in a directory tree

find . | grep -v -f ~/.list_of_files_to_exclude | xargs rm

where ~/.list_of_files_to_exclude is a file with the list of patterns to exclude (one per line)

Before testing it make a backup copy and substitute rm with echo to see if the output is really what you want.

Upvotes: 2

paxdiablo
paxdiablo

Reputation: 882726

White lists for file survival is an incredibly dangerous concept. I would strongly suggest rethinking that.

If you must do it, might I suggest that you actually implement it thus:

  • Move ALL files to a backup area (one created per run such as a directory containing the current date and time).
  • Use your white list to copy back files that you wanted to keep, such as with copy c:\backups\2011_04_07_11_52_04\*.cpp c:\original_dir).

That way, you keep all the non-white-listed files in case you screw up (and you will at some point, trust me) and you don't have to worry about negative logic in your batch file (remove all files that _aren't of all these types), instead using the simpler option (move back every file that is of each type).

Upvotes: 1

Related Questions