How to remove all files in a folder except just some specified files

command linefilesrm

I want to remove all files in a directory while leaving just some specified files, they don't have anything in common by name. How could I achieve that?

For example, the file names I want to keep are:

file_1.png, another_file.jpg, some_music.mp3

Best Answer

If you are using bash:

shopt -s extglob
rm -- !(file1|file2|file3)

The first line just activates extended pattern matching, and after that we use one of them:

!(pattern-list) matches anything except one of the given patterns

and the pattern-list is a list of one or more patterns separated by a |.


Or with zsh

setopt extendedglob
rm -- ^(file1|file2)

Or, more portable, using find:

find . -maxdepth 1 ! -name 'file1' ! -name 'file2' -type f -exec rm -v {} +
Related Question