You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
dotnet-learn-vs/WebMVC/WebMVCApi/md/rm 特殊用法,删除文件夹指定格式的文件.md

80 lines
2.3 KiB
Markdown

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

---
icon: edit
date: 2023-04-06
category:
- Linux
tag:
- rm
- 管道符
- |
- find
- grep
headerDepth: 5
---
# rm 特殊用法,删除文件夹指定格式的文件
rm是我们在Linux下删除文件经常用到的命令但是有时候我们目录下有很多个文件想要删除偏偏却要保留其中1个或几个文件那怎么办呢很多新手朋友可能会采取一个一个文件删除的方法来操作但是如果文件很多呢删到啥时候啊~~
今天我们就来教大家使用rm命令删除文件的时候如何排除指定的文件不删除指定文件。首先我们来看一下平时我们是怎么使用rm命令的。
**1、删除单个文件**
```
rm 1.txt
```
**2、强制删除文件无需确认**
```
rm -rf 1.txt
```
**3、删除文件夹**
```
rm -rf mydir
```
**4、删除目录下全部文件包括文件夹**
```
rm -rf *
```
**5、删除全部文件但保留1.txt**
```
rm -rf !(1.txt)
```
正常情况下是全部文件被删除了只留下了1.txt但是有时候我们的系统没配置好可能会报错例如下面这种
```
root@abc:/home/# rm -rf !(1.txt)
-bash: !: event not found
```
上面这种情况是因为我们的系统没有开启通配符功能,我们执行下面的命令开启通配符功能先:
```
shopt -s extglob
```
查看通配符功能是否开启on表示已经开启
```
shopt -s
```
然后我们再次执行前面的命令就可以看到文件已经全部删除了只保留了1.txt
```
rm -rf !(1.txt)
```
**6、删除全部文件保留1.txt和2.txt**
```
rm -rf !(1.txt|2.txt)
```
上面我们说的都是直接用rm + !(叹号)来排除文件的,下面我们搞个高深一点的,用**find + grep + xargs**三个命令一起用
**7、删除全部文件保留1.txt**
```
find * | grep -v 1.txt | xargs rm
```
这里我们要特别注意grep的-v参数-v参数表示反选比如我们上面指定了-v 1.txt即排除掉1.txt选中其他全部文件。所以这样执行之后1.txt就被排除了
**8、删除全部文件保留1.txt和2.txt**
```
find * | grep -v '\(1.txt\|2.txt\)' | xargs rm
```
**9、删除文件中不包含_字符的文件**
```
find * | grep -v '_' | xargs rm
```
这里要特别留意,括号()跟括号内的竖线|需要添加****进行转义,否则会报错