rm命令删除文件时排除特定文件

# 删除当前目录下所有 *.txt文件,除了test.txt
rm `ls *.txt|egrep -v test.txt`
#或者
rm `ls *.txt|awk '{if($0 != "test.txt") print $0}'`
#排除多个文件
rm `ls *.txt|egrep -v '(test.txt|fff.txt|ppp.txt)'`
rm -f `ls *.log.1|egrep -v '(access-2010-09-06.log|error-2010-09-06.log)'`
rm -f `ls *.log|egrep -v '(access-2010-09-06.log|error-2010-09-06.log)'`
rm -f `ls *.log|egrep -v '(20100906.log)'`

注意:上面所用的符号是‘`’,而不是单引号

rm -rf ls |egrep -v bb 删除所有,保留bb 目录

# 注意:如下这样的写法不生效,因为带有*
rm -rf `ls /tmp/test/apptf/* | egrep -v upload`

# 这样写才可以
rm -rf `ls /tmp/test/apptf/ | egrep -v upload`

# 具体演示
/tmp/test # cd apptf                                                                                                             
/tmp/test/apptf # pwd                                                                                                              
/tmp/test/apptf
/tmp/test/apptf # ll                                                                                                           
总用量 8.0K
drwxrwxr-x  2 root root   41 4月  21 09:45 context
drwxrwxr-x  3 root root   22 4月  21 09:45 export
drwxrwxr-x  2 root root   89 4月  21 09:45 images
-rw-rw-r--  1 root root  345 3月  24 17:44 index.jsp
drwxr-xr-x  3 root root   38 4月  21 09:45 META-INF
drwxrwxr-x 38 root root 4.0K 4月  21 09:45 plug-in
drwxrwxr-x  7 root root  147 4月  21 09:45 swagger
drwxrwxr-x  2 root root   25 4月  21 09:45 swftools
drwxrwxr-x  3 root root   77 4月  21 09:45 upload
drwxrwxr-x  4 root root   62 4月  21 09:45 userfiles
drwxrwxr-x  6 root root   89 4月  21 09:45 WEB-INF
drwxrwxr-x 10 root root  117 4月  21 09:45 webpage

/tmp/test/apptf # rm -rf `ls /tmp/test/apptf/* | egrep -v upload`       # 这个命令执行后只删除index.jsp文件,所有的文件夹都保留了                                                          
/tmp/test/apptf # ll                                                                                                             
总用量 4.0K
drwxrwxr-x  2 root root   41 4月  21 09:45 context
drwxrwxr-x  3 root root   22 4月  21 09:45 export
drwxr-xr-x  3 root root   38 4月  21 09:45 META-INF
drwxrwxr-x 38 root root 4.0K 4月  21 09:45 plug-in
drwxrwxr-x  7 root root  147 4月  21 09:45 swagger
drwxrwxr-x  2 root root   25 4月  21 09:45 swftools
drwxrwxr-x  3 root root   77 4月  21 09:45 upload
drwxrwxr-x  4 root root   62 4月  21 09:45 userfiles
drwxrwxr-x  6 root root   89 4月  21 09:45 WEB-INF
drwxrwxr-x 10 root root  117 4月  21 09:45 webpage
/tmp/test/apptf # rm -rf `ls /tmp/test/apptf/ | egrep -v upload`                                                                   
/tmp/test/apptf # ll                                                                                                               
总用量 0
drwxrwxr-x 3 root root 77 4月  21 09:45 upload
posted @ 2020-04-21 11:01  哈喽哈喽111111  阅读(1697)  评论(0编辑  收藏  举报