Linux面试题(一):删除一个目录下的所有文件,但保留一个指定文件

假设这个目录是/shnne/,里面有log1,log2,log3..log10  十个文件

[root@shnne shnne]# touch log{1..10}
[root@shnne shnne]# ls
log1  log10  log2  log3  log4  log5  log6  log7  log8  log9

 方法一:find

[root@shnne shnne]# ls
log1  log10  log2  log3  log4  log5  log6  log7  log8  log9
[root@shnne shnne]# find /shnne -type f ! -name "log10"|xargs rm -f 
[root@shnne shnne]# ls
log10
[root@shnne shnne]#find ./ -type f|grep -v "log10"|xargs rm -f
 
[root@shnne shnne]# find /shnne -type f ! -name "log10" -exec rm -f {} \;     
[root@shnne shnne]# ls
log10

方法二:rsync

[root@shnne shnne]# ls
log1  log10  log2  log3  log4  log5  log6  log7  log8  log9
[root@shnne shnne]# rsync -az --delete --exclude "log10" /null/ /shnne/
[root@shnne shnne]# ls
log10

方法三:开启bash的extglob功能(此功能的作用就是用rm !(*jpg)这样的方式来删除不包括号内文件的文件)

[root@shnne shnne]# shopt -s extglob
[root@shnne shnne]# ls
log1  log10  log2  log3  log4  log5  log6  log7  log8  log9
[root@shnne shnne]# rm -f !(log10)
[root@shnne shnne]# ls
log10

方法四:

[root@shnne shnne]#rm -f `ls|grep -v "log10"`
分享到:
关键词:Linux运维

网友留言(0 条)

发表评论