4

Usually on bash i did

shopt -s extglob
rm !(filedontwantremove)

and remove all files except filedontwantremove

But if i want to remove all file except filedontwantremove and "antotherfilewithatotaldifferentname"?

There is a find solution,but i prefer i thing like rm !()

elbarna
  • 12,695

2 Answers2

5

Just use:

shopt -s extglob
rm !(filedontwantremove|antotherfilewithatotaldifferentname)

Note however that extglob is usually on by default in interactive shells in bash.
Do this to find out if it is active:

$ shopt -p extglob
shopt -s extglob                    ### The -s means that it is set.

And execute this command to find out the part of the manual that explains what does a !(pattern-list) idiom do:

$ LESS=+/'If the extglob shell option is enabled' man bash

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

1

Yes, there is a find solution, and it's POSIX way:

find . ! -name . -prune -type f ! -name 'file[12]' -exec rm {} +

It's not quite like using globbing, since when it only filtered regular files.

cuonglm
  • 153,898