How to delete all files in a directory except some?

To rm all but u,p in bash just type:

rm !(u|p)

This requires the following option to be set:

shopt -s extglob

See more: glob - Greg's Wiki


What I do in those cases is to type

rm *

Then I press Ctrl+X,* to expand * into all visible file names.

Then I can just remove the two files I like to keep from the list and finally execute the command line.


You can use find

find . ! -name u ! -name p -maxdepth 1 -type f -delete
  • ! negates the next expression
  • -name specifies a filename
  • -maxdepth 1 will make find process the specified directory only (find by default traverses directories)
  • -type f will process only files (and not for example directories)
  • -delete will delete the files

You can then tune the conditions looking at the man page of find

Update

  • Keep in mind that the order of the elements of the expressions is significant (see the documentation)
  • Test your command first by using -print instead of -delete

    find . ! -name u ! -name p -maxdepth 1 -type f -print
    

Tags:

Linux

Bash

Rm