从目录中删除除某些文件以外的所有文件 [英] Remove all files except some from a directory

查看:166
本文介绍了从目录中删除除某些文件以外的所有文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用sudo rm -r时,如何删除所有文件,但以下情况除外:

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

推荐答案

find [path] -type f -not -name 'textfile.txt' -not -name 'backup.tar.gz' -delete

如果您未指定-type f,则find还将列出您可能不需要的目录.

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

或者使用非常有用的组合find | xargs的更通用的解决方案:

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

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

例如,删除当前目录中的所有非txt文件:

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

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

如果任何文件名中有空格都应删除,则需要print0-0组合.

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

这篇关于从目录中删除除某些文件以外的所有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆