Linux 通配符完全指南:从基础语法到实战应用

Linux 通配符完全指南:从基础语法到实战应用

什么是通配符?

通配符是一组规则符号,用于创建定义文件或目录集合的模式。正如你所知,在命令行中引用文件或目录时,实际是在引用路径。而在路径中使用通配符,可以将其转换为一组文件或目录。

基本通配符集合:

  • *:匹配零个或多个字符
  • ?:匹配单个字符
  • []:匹配范围内的单个字符

基础示例

*为例,以下命令将列出所有以字母b开头的条目:

1
2
3
4
5
6
7
8

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 bob

底层原理

这里的机制很有趣:你可能以为ls命令会直接处理b*参数,但实际上是bash(提供命令行界面的程序)完成了模式匹配。当输入包含通配符的命令时,系统会先将模式替换为所有匹配的文件或目录路径,再执行命令。例如:

1
2
3
4
5
6

# 输入命令
ls b*
# 系统转换为
ls barry.txt blah.txt bob
# 再执行程序

因此,通配符可在任何命令行中使用,不受程序限制。

更多示例

假设当前目录为linuxtutorialwork,且包含上述文件,以下是通配符的应用场景:

    1. 匹配所有.txt后缀文件(绝对路径)
1
2
3

ls /home/ryan/linuxtutorialwork/*.txt
/home/ryan/linuxtutorialwork/barry.txt /home/ryan/linuxtutorialwork/blah.txt
    1. 匹配第二个字母为i的文件(?通配符)
1
2
3

ls ?i*
firstfile video.mpeg
    1. 匹配三字母后缀的文件(.???)
1
2
3

ls *.???
barry.txt blah.txt example.png frog.png

注意:video.mpeg后缀为.mpeg,四字母,不匹配

    1. 匹配以s或v开头的文件([]范围匹配)
1
2
3

ls [sv]*
secondfile video.mpeg
    1. 匹配包含数字的文件([0-9]范围)
1
2
3

ls *[0-9]*
foo1 foo2 foo3
    1. 匹配非a-k开头的文件([^]取反)
1
2
3

ls [^a-k]*
secondfile thirdfile video.mpeg

实际应用场景

通配符的用途极为广泛,以下是几个典型案例:

    1. 查看目录中所有文件的类型
1
2
3
4
5
6

file /home/ryan/*
bin: directory
Documents: directory
frog.png: PNG image data
public_html: directory
    1. 将所有jpg/png图片移动到指定目录
1
2

mv public_html/*.??g public_html/images/
    1. 查看所有用户家目录中的.bash_history文件
1
2
3
4

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_history