使用sudo rm -r时,如何删除除以下文件外的所有文件?
textfile.txt
backup.tar.gz
script.php
database.sql
info.txt
使用sudo rm -r时,如何删除除以下文件外的所有文件?
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也会列出目录,这可能不是您想要的。
或者一个更通用的解决方案,使用非常有用的组合find | xargs:
find [path] -type f -not -name 'EXPR' -print0 | xargs -0 rm --
例如,删除当前目录下的所有非txt文件:
find . -type f -not -name '*txt' -print0 | xargs -0 rm --
如果需要删除的文件名中有空格,则需要print0和-0组合。
其他回答
在Bash中可以使用GLOBIGNORE环境变量。
假设您想删除除php和sql之外的所有文件,那么您可以执行以下操作-
export GLOBIGNORE=*.php:*.sql
rm *
export GLOBIGNORE=
像这样设置GLOBIGNORE会忽略php和sql中的通配符,比如“ls *”或“rm *”。因此,在设置变量后使用“rm *”将只删除txt和tar.gz文件。
使文件不可变。即使root用户也不允许删除它们。
chattr +i textfile.txt backup.tar.gz script.php database.sql info.txt
rm *
所有其他文件都已删除。 最终你可以将它们重置为可变的。
chattr -i *
我正在寻找的答案是运行脚本,但我希望避免删除脚本本身。因此,如果有人正在寻找类似的答案,请执行以下步骤。
创建一个.sh文件并编写以下代码:
cp my_run_build.sh ../../
rm -rf * cp
../../my_run_build.sh .
/*amend rest of the script*/
由于还没有人提到这一点,在一个特定的案例中:
OLD_FILES=`echo *`
... create new files ...
rm -r $OLD_FILES
(或者只是rm $OLD_FILES)
or
OLD_FILES=`ls *`
... create new files ...
rm -r $OLD_FILES
你可能需要使用shop -s nullglob,如果一些文件可能在那里或不在那里:
SET_OLD_NULLGLOB=`shopt -p nullglob`
shopt -s nullglob
FILES=`echo *.sh *.bash`
$SET_OLD_NULLGLOB
如果没有nullglob,则echo *.sh *。Bash可能会给你“a.sh b.sh *. Bash”。
(说了这么多,我自己更喜欢这个答案,即使它在OSX中不起作用)
这类似于@siwei-shen的评论,但是您需要-o标志来处理多个模式。-o标志代表'or'
找到。-o -not -name '*ignore2' | xargs rm . type f -not -name '*ignore1' -o -not -name '*ignore2