I need to delete all files in a directory, but exclude some of them. For example, in a directory with the files a b c ... z, I need to delete all except for u and p. Is there an easy way to do this?
|
What I do in those cases is to type
Then I press Ctrl+X,* to expand Then I can just remove the two files I like to keep from the list and finally execute the command line. |
|||||||||||||||||
|
|
To
This requires the following option to be set:
See more: glob - Greg's Wiki |
||||
|
Simple:
|
|||||||||||||||
|
|
You can use
You can then tune the conditions looking at the man page of find Update
|
|||||||||||||||
|
|
Somewhat similar to this answer but no special options are needed, as far as I know the following is "ancient" functionality supported by any (vaguely) /bin/sh resembling shell (e.g. bash, zsh, ksh, etc)
|
|||||||||||||||||||
|
|
GLOBIGNORE takes a colon-separated list
|
|||||
|
|
Doing it without find:
(Edit: "u" and "v", as in other places here, are being used as generic versions of entire regexes. Obviously you'll want to be careful to anchor your regexes to avoid matching too many things.) You're definitely going to want a script if you're going to be doing much of this, as others have suggested. |
|||||||||||||||
|
|
Back in the floppy era I had a dos executable called "Except" that would move things out of the current directory temporarially and execute a command, so you could say: except *.txt del *.* to delete everything but your text files. This would be a pretty trivial thing to implement as a shell script and if this is the kind of thing you are likely to do more than twice it seems like it would be a good idea. |
|||||
|
|
In zsh:
then
or
The second will work even if you have |
|||
|
|
This will delete all files except u and p in unix |
||||
|
|
|
For those preferring to specify arbitrary complex exclude patterns (spanning all affected filenames) in a full blown regexp emacs, posix-awk or posix-extended style (see find man page) I would recommend this one. It excludes
|
||||
|
I always use:
This will allow you to define how granular you want to make it. So if you want to delete a through o and Z files you can use:
|
|||
|
|
|
Yet another version using
Note that |
|||
|
|

shopt -s dotglobbefore runningrm (...). – jameswarden Jan 28 at 8:07