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 !()

2
  • 3
    info bash says: "In the following description, a PATTERN-LIST is a list of one or more patterns separated by a '|' ..." Feb 21, 2016 at 1:59
  • There's also GLOBIGNORE: unix.stackexchange.com/a/1174/70524
    – muru
    Feb 21, 2016 at 2:15

2 Answers 2

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.