Understanding Glob Patterns
Glob Patterns
Glob patterns are a simple yet powerful way to match file names and paths using wildcard characters. They are commonly used in command-line interfaces and programming languages to specify sets of filenames or directories. Hereโs a breakdown of the most commonly used glob patterns:
Basic Wildcards
-
*
: Matches any number of characters, including zero characters.- Example:
*.txt
matches all files ending with.txt
.
- Example:
-
?
: Matches exactly one character.- Example:
file?.txt
matchesfile1.txt
,fileA.txt
, but notfile10.txt
.
- Example:
-
[]
: Matches any one of the enclosed characters.- Example:
file[1-3].txt
matchesfile1.txt
,file2.txt
,file3.txt
.
- Example:
-
[!]
or[^]
: Matches any character not enclosed.- Example:
file[!1-3].txt
matchesfile4.txt
,fileA.txt
, but notfile1.txt
.
- Example:
Advanced Patterns
-
**
: Matches any number of directories and subdirectories recursively.- Example:
**/*.txt
matches all.txt
files in the current directory and all subdirectories.
- Example:
-
{}
: Matches any of the comma-separated patterns enclosed.- Example:
file{1,2,3}.txt
matchesfile1.txt
,file2.txt
,file3.txt
.
- Example:
Examples
-
Matching all text files in a directory:
Terminal window *.txt -
Matching all files with a single digit before the extension:
Terminal window file?.txt -
Matching files with extensions
.jpg
or.png
:Terminal window *.{jpg,png} -
Matching all
.txt
files in any subdirectory:Terminal window **/*.txt -
Matching files that start with
a
orb
and end with.txt
:Terminal window {a,b}*.txt
Use Cases
- Command-Line Tools: Glob patterns are extensively used in command-line tools like
ls
,cp
,mv
, andrm
to specify multiple files or directories. - Programming Languages: Languages like Python, JavaScript, and Ruby support glob patterns for file matching through libraries like
glob
in Python. - Build Systems: Tools like Makefile use glob patterns to specify source files and dependencies.
Conclusion
Glob patterns provide a flexible and intuitive way to match filenames and paths, making them invaluable for scripting, automation, and file management tasks. Understanding and utilizing these patterns can significantly enhance your productivity and efficiency in handling files and directories.