Login Register

How do I remove all files in a folder except just some specified files?

Sometimes you get into a situation where you need to delete all files in a directory or clean up a guide by removing all files except some specified files.

Here are two methods you can try:

  • You can use the bash GLOBIGNORE variable to remove all files except specific ones—a colon-separated list of patterns defining the set of filenames to be ignored by pathname expansion. If a filename matched by a pathname expansion pattern also matches one of the patterns in GLOBIGNORE, it is removed from the list of matches.

To delete all files except zipping and iso files, set GLOBIGNORE as follows:

## only works with BASH ##

cd ~/Downloads/

GLOBIGNORE=*.zip:*.iso

rm -v *

unset GLOBIGNORE

  • Add the names of the files you want to keep to a text file, one per line. This file should not be in the directory, or you should add its name too.

If the name of your directory is foo and the name of the file is a bar, do the following.

find foo-type f -print0|grep -vzZ -f bar|xargs -0 rm

It does the following:

  1. Find -type f searches for the names of all files in foo and its subdirectories and prints them to STDOUT. With option -print0, it delimits the filenames with NUL bytes.
  2. Grep -v -f bar excludes all filenames that match a line in the bar. With option -z, it treats its input as a set of strings delimited by NUL byte; with option -Z, it delimits its output with a NUL byte.
  3. xargs rm calls rm repeatedly to delete the files. With option -0, it treats its input as a set of lines delimited by the NUL byte.

It works with filenames containing white space.