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

先给出一种最简单的方式来实现:

比如现在在目录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 "\boldboy1\b"|xargs rm -f
 
方法五:
rm -f `ls|grep -v "\boldboy1\b"`


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值