In the UNIX shell how should I remove everything from a directory except a certain number of files?
For example, how would I remove every file and folder but the folder
If there's also an equivalent for DOS shell, what is it?
First, test with:
-maxdepth 1 means to look in the current folder only (and it needs to be the first option)
! -iname (or -name) says to not include anything that matches what you want to stay.
-type f makes sure you don't get any directories in the current folder.
Be sure to double check it first with some test data!
To match everything but something is generally referred to as an inverse match. To expand filename is the shell itself you use globbing. If you are going to call a program outside of the shell you would probably want find as people have mentioned.
You can do an inverse match with a newer bash if you enable extended globbing. For example, to match everything that doesn't have foo or bar in the name:
Or just everything that doesn't have foo:
If there are no open files in
I don't think there is an easy "negative" match in
edit: just a thought...
will list all the files except foo, so you could use
though that will have problems if any of the file/directory names contain spaces.
Be very careful to test the output of the find+grep sequence before adding the
If it were a small list, I would do something like:
Which gets the list of files, then greps for the regex excluding the files you want to keep, and removes everything else.
You should DEFINITELY test this by leaving off the xargs part to verify you have the right set of files.
There is also a more casual solution, which is:
The disadvantage is that your precious files are momentarily displaced. This solution would not be suitable if your precious files must be available the entire time.
However, this method has the advantage that you can verify after step 2 that your precious files are safe. This is particularly significant if there are hidden files or subdirectories involved, which would raise the chances of making a mistake with the other methods suggested here.
Version for Windows cmd.exe
Print the names of all directories in C:\ except those called 'foo':
Print the names of all files in C:\ except those called 'foo' (ignoring file extensions):
Print the names of all files in C:\ except those with the extension 'bar':
Print the names of all files in C:\ except those called 'foo.bar':
Change the 'echo' command to whatever it is that you want to do - e.g. 'del'
All of the above are case INsensitive - remove '/I' to change this.
Type 'for /?' for more details on FOR's %~ syntax.