rm [option] filename
不过,使用上述命令删除文件的时候,需要知道确切的文件名。那么怎样根据文件扩展名来删除多个文件呢?今天我们来介绍几种方法。
方法1:使用 rm 命令按扩展名删除文件
rm *.gif
ls *.gif
通常情况下,我在删除文件的时候会做如下操作:
$ ls1.gif 2.gif 3.gif 4.gif a.jpg b.png c.webp$ ls *.gif1.gif 2.gif 3.gif 4.gif$ rm -v *.gifremoved '1.gif'removed '2.gif'removed '3.gif'removed '4.gif'$ lsa.jpg b.png c.webp
$ lsf1.txt f2.txt f3.txt f4.txt not-txt-file.pdf random.txt$ rm -v *.txt *.pdfremoved 'f1.txt'removed 'f2.txt'removed 'f3.txt'removed 'f4.txt'removed 'not-txt-file.pdf'$ lsrandom.txt
在使用 rm 命令的时候,可以使用交互式的 -i 选项,该选项要求在删除文件之前进行确认。不过这个适用于删除单个或者几个文件,如果批量删除文件,这个选项就不方便了。
像上面的删除操作,它具体是怎样工作的呢?答案是使用的通配符。
简而言之,通配符是用于匹配特定模式的特殊字符。以下是一些常用的通配符:
| 通配符 | 用途 |
| * | 匹配一个或多个匹配项 |
| ? | 匹配单个 |
| [] (方括号) | 指定匹配范围 |
| ^ | 从匹配中排除 |
在上面的删除例子中,我们使用了 * 通配符,这表示它可以匹配任何字符。当你使用 *.gif 的时候,它实际表示的是与 .gif 组合的任何字符,也就是说,它提供了所有以 gif 为扩展名的文件。
* 和扩展名之间的点很重要
有些人在使用通配符的时候,会这样写:*gif,这是不对的。* 和扩展名之间的点 . 至关重要。
看下面的例子,假如我们使用 *gif 来删除文件,看看会怎样。
$ ls1.gif 2.gif 3.gif 4.gif definately-not-a-gif jpg-not-gif not-a-gif$ rm -v *gifremoved '1.gif'removed '2.gif'removed '3.gif'removed '4.gif'removed 'definately-not-a-gif'removed 'jpg-not-gif'removed 'not-a-gif'
可以看到,除了删除所有 gif 文件外,它还删除了文件名中带有字符串 gif 的文件,尽管它不是文件的扩展名。所以,删除带有通配符或正则表达式的文件时,应确保尽可能精确。
方法2:使用find命令递归删除具有特定扩展名的文件
rm 命令仅删除当前目录中的文件。即使使用递归选项,它也不会从子目录中删除文件。
要递归删除具有特定扩展名的文件,可以组合find命令和rm命令。看下面的例子,在子目录中也有 .gif 文件:
$ ls *file_0.gif file_z.txt not-a-gif not-a-txtdir1:file_1.gif file_a.txt not-a-gif not-a-txtdir2:file_2.gif file_b.txt not-a-gif not-a-txtdir3:file_3.gif file_c.txt not-a-gif not-a-txtdir4:file_4.gif file_d.txt not-a-gif not-a-txt
find . -type f -name "*.gif" -exec rm -v {} \;
$ find . -type f -name "*.gif" -exec rm -v {} \;removed './dir1/file_1.gif'removed './dir3/file_3.gif'removed './dir2/file_2.gif'removed './file_0.gif'removed './dir4/file_4.gif
下面我们拆开来说明下:
find 后面的点 . 表示在当前目录中搜索;
-name 选项指定文件的名称,我们可以在其中使用正则表达式;
-exec 选项用于对 find 命令的结果执行 bash 命令;
{} 大括号充当匹配文件结果的占位符,因此 rm-v {} 将删除find命令找到的文件;
最后,分号结束 shell 执行的命令(exec之后的命令),并使用反斜杠 \,以便正确转义分号。
使用 find 命令处理多个扩展名文件
上面显示的命令不包括查找具有多个扩展名的文件,如:rm *.gif *.txt
要实现这一点,可以使用 -o 参数,它表示逻辑或运算符,但需要用括号括起来,且必须使用反斜杠 \ 来转义括号。
$ ls *file_0.gif file_z.txt not-a-gif not-a-txtdir1:file_1.gif file_a.txt not-a-gif not-a-txtdir2:file_2.gif file_b.txt not-a-gif not-a-txtdir3:file_3.gif file_c.txt not-a-gif not-a-txtdir4:file_4.gif file_d.txt not-a-gif not-a-txt$ find . \( -name "*.gif" -o -name "*.txt" \) -exec rm -v {} \;removed './dir1/file_1.gif'removed './dir1/file_a.txt'removed './dir3/file_3.gif'removed './dir3/file_c.txt'removed './dir2/file_2.gif'removed './dir2/file_b.txt'removed './file_0.gif'removed './file_z.txt'removed './dir4/file_d.txt'removed './dir4/file_4.gif'
在这里,我们可以看到所有扩展名为 txt 的文件和扩展名为 gif 的文件都被递归删除。
大家可能会觉得对每个文件扩展名类型单独使用 find 命令会更容易,实际上也是这样的...
推荐阅读:




