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:21

Since no one yet mentioned this, in one particular case:

OLD_FILES=`echo *`
... create new files ...
rm -r $OLD_FILES

(or just rm $OLD_FILES)

or

OLD_FILES=`ls *`
... create new files ...
rm -r $OLD_FILES

You may need to use shopt -s nullglob if some files may be either there or not there:

SET_OLD_NULLGLOB=`shopt -p nullglob`
shopt -s nullglob
FILES=`echo *.sh *.bash`
$SET_OLD_NULLGLOB

without nullglob, echo *.sh *.bash may give you "a.sh b.sh *.bash".

(Having said all that, I myself prefer this answer, even though it does not work in OSX)

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-01-08 03:25

You can use GLOBIGNORE environment variable in Bash.

Suppose you want to delete all files except php and sql, then you can do the following -

export GLOBIGNORE=*.php:*.sql
rm *
export GLOBIGNORE=

Setting GLOBIGNORE like this ignores php and sql from wildcards used like "ls *" or "rm *". So, using "rm *" after setting the variable will delete only txt and tar.gz file.

查看更多
老娘就宠你
4楼-- · 2019-01-08 03:27

If you're using zsh which I highly recommend.

rm -rf ^file/folder pattern to avoid

With extended_glob

setopt extended_glob
rm -- ^*.txt
rm -- ^*.(sql|txt)
查看更多
走好不送
5楼-- · 2019-01-08 03:28

Make the files immutable. Not even root will be allowed to delete them.

chattr +i textfile.txt backup.tar.gz script.php database.sql info.txt
rm *

All other files have been deleted.
Eventually you can reset them mutable.

chattr -i *
查看更多
疯言疯语
6楼-- · 2019-01-08 03:30

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

查看更多
Rolldiameter
7楼-- · 2019-01-08 03:31

Remove everything exclude file.name:

ls -d /path/to/your/files/* |grep -v file.name|xargs rm -rf
查看更多
登录 后发表回答