Back

Removing files with exclusions

To remove all but one/some file(s) in zsh, run:

rm -f -- path/to/files/^(fileToExclude1|fileToExclude2)

Exclusions can be wildcarded too, e.g.:

rm -f -- path/to/files/^(fileToExclude*)

The same can be achieved in bash by replacing ^ with !

EDIT (17/10/2022): Extended globbing (pathname expansion) for bash and zsh must be enabled for the above to work. Respectively:

shopt -s extglob

and

setopt extendedglob

EDIT (28/06/2023): An even better way of achieving this in zsh is to use array difference expansion and put it into a shell function:

remove-excluding() { ‎ ‎ ‎ ‎ typeset -a allfiles=(*) ‎ ‎ ‎ ‎ rm -f -- ${allfiles:|argv} }

where the first line sets an array variable called allfiles which as the name suggests, contains all filenames in the current directory. The second line uses an array difference expansion operator (:|) to exclude function's arguments from the final list of files to remove. This can be simply used as such:

remove-excluding file1.txt file\ number\ two.jpeg

More explanation can be found here


Original publication date: 28/09/22 21:57:44
Last edit date: 28/06/23 20:08:11