Linux 通配符完全指南:从基础语法到实战应用
在文件操作章节中,我们学习了一些实用命令,但它们一次只能操作单个文件,效率不高。现在我将介绍一种批量处理文件的方法。
什么是通配符?通配符是一组规则符号,用于创建定义文件或目录集合的模式。正如你所知,在命令行中引用文件或目录时,实际是在引用路径。而在路径中使用通配符,可以将其转换为一组文件或目录。
基本通配符集合:
*:匹配零个或多个字符 ?:匹配单个字符 []:匹配范围内的单个字符以*为例,以下命令将列出所有以字母b开头的条目:
复制
pwd
/home/ryan/linuxtutorialwork
ls
barry.txt blah.txt bob example.png firstfile foo1 foo2
foo3 frog.png secondfile thirdfile video.mpeg
ls b*
barry.txt blah.txt bob1.2.3.4.5.6.7.
这里的机制很有趣:你可能以为ls命令会直接处理b*参数,但实际上是bash(提供命令行界面的程序)完成了模式匹配。当输入包含通配符的命令时,系统会先将模式替换为所有匹配的文件或目录路径,再执行命令。例如:
复制
# 输入命令
ls b*
# 系统转换为
ls barry.txt blah.txt bob
# 再执行程序1.2.3.4.5.
因此,通配符可在任何命令行中使用,不受程序限制。
更多示例假设当前目录为linuxtutorialwork,且包含上述文件,以下是通配符的应用场景:
(1) 匹配所有.txt后缀文件(绝对路径)
复制
ls /home/ryan/linuxtutorialwork/*.txt
/home/ryan/linuxtutorialwork/barry.txt /home/ryan/linuxtutorialwork/blah.txt1.2.
(2) 匹配第二个字母为i的文件(?通配符)
复制
ls ?i*
firstfile video.mpeg1.2.
(3) 匹配三字母后缀的文件(.???)
复制
ls *.???
barry.txt blah.txt example.png frog.png1.2.
注意:video.mpeg后缀为.mpeg,四字母,不匹配
(4) 匹配以s或v开头的文件([]范围匹配)
复制
ls [sv]*
secondfile video.mpeg1.2.
(5) 匹配包含数字的文件([0-9]范围)
复制
ls *[0-9]*
foo1 foo2 foo31.2.
(6) 匹配非a-k开头的文件([^]取反)
复制
ls [^a-k]*
secondfile thirdfile video.mpeg1.2.
通配符的用途极为广泛,以下是几个典型案例:
(1) 查看目录中所有文件的类型
复制
file /home/ryan/*
bin: directory
Documents: directory
frog.png: PNG image data
public_html: directory1.2.3.4.5.
(2) 将所有jpg/png图片移动到指定目录
复制
mv public_html/*.??g public_html/images/1.
(3) 查看所有用户家目录中的.bash_history文件
复制
ls -lh /home/*/.bash_history
-rw------- 1 harry users 2.7K Jan 4 07:32 /home/harry/.bash_history
-rw------- 1 ryan users 3.1K Jun 12 21:16 /home/ryan/.bash_history1.2.3.
THE END