1、创建测试数据



[root@centos7 test2]# touch {1..9}.txt
[root@centos7 test2]# ls
1.txt 2.txt 3.txt 4.txt 5.txt 6.txt 7.txt 8.txt 9.txt


 

2、删除3.txt、7.txt外的其他文件



[root@centos7 test2]# ls | grep -v "3.txt"
1.txt
2.txt
4.txt
5.txt
6.txt
7.txt
8.txt
9.txt
[root@centos7 test2]# ls | grep -v "3.txt" | grep -v "7.txt"
1.txt
2.txt
4.txt
5.txt
6.txt
8.txt
9.txt
[root@centos7 test2]# ls | grep -v "3.txt" | grep -v "7.txt" | xargs rm -f
[root@centos7 test2]# ls
3.txt 7.txt


 

3、扩展grep



[root@centos7 test2]# touch {1..9}.txt
[root@centos7 test2]# ls
1.txt 2.txt 3.txt 4.txt 5.txt 6.txt 7.txt 8.txt 9.txt
[root@centos7 test2]# ls | grep -v -E "3.txt|7.txt" | xargs rm -f
[root@centos7 test2]# ls
3.txt 7.txt


 

4、



[root@centos7 test2]# touch {1..9}.txt
[root@centos7 test2]# ls
1.txt 2.txt 3.txt 4.txt 5.txt 6.txt 7.txt 8.txt 9.txt
[root@centos7 test2]# rm -rf !(3.txt)
[root@centos7 test2]# ls
3.txt


 



[root@centos7 test2]# touch {1..9}.txt
[root@centos7 test2]# ls
1.txt 2.txt 3.txt 4.txt 5.txt 6.txt 7.txt 8.txt 9.txt
[root@centos7 test2]# rm -rf !(2.txt|7.txt)
[root@centos7 test2]# ls
2.txt 7.txt