在Linux下删除 除了某个文件之外的所有文件/目录

2019-07-12 21:07发布

先给出一种最简单的方式来实现:
比如现在在目录temp下有a、b、c三个文件,如何一行命令删除b和c,不删除a,本文将介绍该实现方法。  其中rm -f  !(a) 最为方便。如果保留a和b,可以运行rm -f !(a|b)来实现。 不过一般bash中运行后会提示 “-bash: !: event not found ” 可以通过运行shopt -s extgolb来解决。
下面是给出其他几种方法(其中主要方法五中的` `不是单引号,而是Esc下边的那个键): 假设这个目录是/xx/,里面有file1,file2,file3..file10 十个文件 [root@ xx]# touch file{1..10} [root@ xx]# ls file1 file10 file2 file3 file4 file5 file6 file7 file8 file9 方法一:find [root@ xx]# ls file1 file10 file2 file3 file4 file5 file6 file7 file8 file9 [root@ xx]# find /xx -type f ! -name "file10"|xargs rm -f [root@ xx]# ls file10 [root@ xx]# find /xx -type f ! -name "file10" -exec rm -f {} ; [root@ xx]# ls file10 这两种一个通过xargs传参,一个通过find的-exec执行命令参数来完成,都算作find吧 方法二:rsync [root@ xx]# ls file1 file10 file2 file3 file4 file5 file6 file7 file8 file9 [root@ xx]# rsync -az --delete --exclude "file10" /null/ /xx/ [root@ xx]# ls file10 方法三:开启bash的extglob功能(此功能的作用就是用rm !(*jpg)这样的方式来删除不包括号内文件的文件) [root@ xx]# shopt -s extglob [root@ xx]# ls file1 file10 file2 file3 file4 file5 file6 file7 file8 file9 [root@ xx]# rm -f !(file10) [root@ xx]# ls file10 方法四: find ./ -type f|grep -v "oldboy1"|xargs rm -f 方法五: rm -f `ls|grep -v "oldboy1"`