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

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。