Remove all files except some from a directory

2019-01-08 03:05发布

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

标签: bash rm
18条回答
霸刀☆藐视天下
2楼-- · 2019-01-08 03:14
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.

查看更多
疯言疯语
3楼-- · 2019-01-08 03:17
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
查看更多
三岁会撩人
4楼-- · 2019-01-08 03:18

Trying it worked with:

rm -r !(Applications|"Virtualbox VMs"|Downloads|Documents|Desktop|Public)

but names with spaces are (as always) tough. Tried also with Virtualbox\ VMs instead the quotes. It deletes always that directory (Virtualbox VMs).

查看更多
看我几分像从前
5楼-- · 2019-01-08 03:18

Rather than going for a direct command, please move required files to temp dir outside current dir. Then delete all files using rm * or rm -r *.

Then move required files to current dir.

查看更多
乱世女痞
6楼-- · 2019-01-08 03:19

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
查看更多
闹够了就滚
7楼-- · 2019-01-08 03:20

Since nobody mentioned it:

  • copy the files you don't want to delete in a safe place
  • delete all the files
  • move the copied files back in place
查看更多
登录 后发表回答