linux中删除目录中指定文件外的其他文件

 

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

 

posted @ 2021-04-15 09:05  小鲨鱼2018  阅读(329)  评论(0编辑  收藏  举报