Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all files except some from a directory

Tags:

bash

rm

People also ask

How do I delete all files except a specific file extension?

Highlight all the files you want to keep by clicking the first file type, hold down the Shift key, and click the last file. Once all the files you want to keep are highlighted, on the Home Tab, click Invert Selection to select all other files and folders.

How do I select all files except one?

Click the first file or folder you want to select. Hold down the Shift key, select the last file or folder, and then let go of the Shift key. Hold down the Ctrl key and click any other file(s) or folder(s) you would like to add to those already selected.


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.


rm !(textfile.txt|backup.tar.gz|script.php|database.sql|info.txt)

The extglob (Extended Pattern Matching) needs to be enabled in BASH (if it's not enabled):

shopt -s extglob

find . | grep -v "excluded files criteria" | xargs rm

This will list all files in current directory, then list all those that don't match your criteria (beware of it matching directory names) and then remove them.

Update: based on your edit, if you really want to delete everything from current directory except files you listed, this can be used:

mkdir /tmp_backup && mv textfile.txt backup.tar.gz script.php database.sql info.txt /tmp_backup/ && rm -r && mv /tmp_backup/* . && rmdir /tmp_backup

It will create a backup directory /tmp_backup (you've got root privileges, right?), move files you listed to that directory, delete recursively everything in current directory (you know that you're in the right directory, do you?), move back to current directory everything from /tmp_backup and finally, delete /tmp_backup.

I choose the backup directory to be in root, because if you're trying to delete everything recursively from root, your system will have big problems.

Surely there are more elegant ways to do this, but this one is pretty straightforward.


I prefer to use sub query list:

rm -r `ls | grep -v "textfile.txt\|backup.tar.gz\|script.php\|database.sql\|info.txt"`

-v, --invert-match select non-matching lines

\| Separator


Assuming that files with those names exist in multiple places in the directory tree and you want to preserve all of them:

find . -type f ! -regex ".*/\(textfile.txt\|backup.tar.gz\|script.php\|database.sql\|info.txt\)" -delete