Skip to content

Glob Patterns

Globs, also known as glob patterns are patterns that can expand a wildcard pattern into a list of pathnames that match the given pattern.

A glob pattern is a pattern that specifies sets of filenames with wildcard characters. Wildcard characters can match zero or more characters in a path segment, such as * or ?, or any number of path segments, such as **. Glob patterns are used to expand a wildcard pattern into a list of pathnames that match the given pattern. For example, the glob pattern *.txt matches all files with names ending in .txt.

以下表述含义相同:

Globs = Glob patterns
Wildcards = Wildcard characters = * and ?

通配符早于正则表达式出现,可以看作是原始的正则表达式。

基础语法

glob 模式匹配大致可以分为以下两种情况:

  • 通配符
    • ? matches any character exactly once
    • * matches a string of zero or more characters.
  • 字符组/字符集合/字符区间
    • [...]

归纳为以下表格:

通配符匹配模式
*匹配 0 个或多个字符
?匹配 1 个字符
[abc]匹配方括号内字符集合中的单个字符
[a-z]匹配方括号内字符区间中的单个字符
[^abc][!abc]匹配非方括号内字符集合中的单个字符
[^a-z][!a-z]匹配非方括号内字符区间中的单个字符

扩展语法

扩展语法,主要包含三种:

  • Brace Expansion
  • globstar
  • extglob

应用实例

glob 模式匹配最常见的应用场景是匹配文件路径,使用 glob 匹配文件路径比正则表达式更简洁。一般情况下,通配符不会匹配文件路径分隔符 (/ on Linux/Unix, MacOS, etc. or \ on Windows) 。

  • *.md: 匹配当前目录下,所有以 .md 结尾的 Markdown 文件
  • **/*.md: 匹配当前目录下,以及各级子目录下的,所有以 .md 结尾的 Markdown 文件

扩展阅读

有效的 glob 模式

  • 字母数字字符 (A-Za-z0-9)、下划线 (_)、连字符 (-) 和点号 (.) 必须逐字匹配
  • 特殊 glob 字符 *?** 和字符集合 [...]:在 [...] 内,连字符使用在中间时 - 表示范围(例如 a-z,根据 Unicode 码点排序),使用在开头或结尾时,则按字面量进行匹配
  • 路径分隔符必须是正斜线字符 (/)
  • 模式使用的路径永远是相对路径,模式应总是相对于包含该文件的目录;因此,不得使用前导斜线字符
  • 不得使用父目录指示符 (..)
最近更新