Remove all files except some from a directory

masjoko picture masjoko · Dec 1, 2010 · Viewed 190.1k times · Source

When using sudo rm -r, how can I delete all files, with the exception of the following:

textfile.txt
backup.tar.gz
script.php
database.sql
info.txt

Answer

awi picture awi · Dec 1, 2010
find [path] -type f -not -name 'textfile.txt' -not -name 'backup.tar.gz' -delete

If you don't specify -type f find will also list directories, which you may not want.


Or a more general solution using the very useful combination find | xargs:

find [path] -type f -not -name 'EXPR' -print0 | xargs -0 rm --

for example, delete all non txt-files in the current directory:

find . -type f -not -name '*txt' -print0 | xargs -0 rm --

The print0 and -0 combination is needed if there are spaces in any of the filenames that should be deleted.