glob (programming)

From HandWiki
Short description: Patterns used in computer programming

In computer programming, glob (/ɡlɒb/) patterns specify sets of filenames with wildcard characters. For example, the Unix Bash shell command mv *.txt textfiles/ moves all files with names ending in .txt from the current directory to the directory textfiles. Here, * is a wildcard and *.txt is a glob pattern. The wildcard * stands for "any string of any length including empty, but excluding the path separator characters (/ in unix and \ in windows)".

The other common wildcard is the question mark (?), which stands for one character. For example, mv ?.txt shorttextfiles/ will move all files named with a single character followed by .txt from the current directory to directory shorttextfiles, while ??.txt would match all files whose name consists of 2 characters followed by .txt.

In addition to matching filenames, globs are also used widely for matching arbitrary strings (wildcard matching). In this capacity a common interface is fnmatch.

Origin

A screenshot of the original 1971 Unix reference page for glob – the owner is dmr, short for Dennis Ritchie.

The glob command, short for global, originates in the earliest versions of Bell Labs' Unix.[1] The command interpreters of the early versions of Unix (1st through 6th Editions, 1969–1975) relied on a separate program to expand wildcard characters in unquoted arguments to a command: /etc/glob. That program performed the expansion and supplied the expanded list of file paths to the command for execution.

Glob was originally written in the B programming language. It was the first piece of mainline Unix software to be developed in a high-level programming language.[2] Later, this functionality was provided as a C library function, glob(), used by programs such as the shell. It is usually defined based on a function named fnmatch(), which tests for whether a string matches a given pattern - the program using this function can then iterate through a series of strings (usually filenames) to determine which ones match. Both functions are a part of POSIX: the functions defined in POSIX.1 since 2001, and the syntax defined in POSIX.2.[3][4] The idea of defining a separate match function started with wildmat (wildcard match), a simple library to match strings against Bourne Shell globs.

Traditionally, globs do not match hidden files in the form of Unix dotfiles; to match them the pattern must explicitly start with .. For example, * matches all visible files while .* matches all hidden files.

Syntax

The most common wildcards are *, ?, and […].

Wildcard Description Example Matches Does not match
* matches any number of any characters including none Law* Law, Laws, or Lawyer GrokLaw, La, or aw
*Law* Law, GrokLaw, or Lawyer. La, or aw
? matches any single character ?at Cat, cat, Bat or bat at
[abc] matches one character given in the bracket [CB]at Cat or Bat cat, bat or CBat
[a-z] matches one character from the (locale-dependent) range given in the bracket Letter[0-9] Letter0, Letter1, Letter2 up to Letter9 Letters, Letter or Letter10

Normally, the path separator character (/ on Linux/Unix, MacOS, etc. or \ on Windows) will never be matched. Some shells, such as Bash have functionality allowing users to circumvent this.[5]

Unix-like

On Unix-like systems *, ? is defined as above while […] has two additional meanings:[6][7]

Wildcard Description Example Matches Does not match
[!abc] matches one character that is not given in the bracket [!C]at Bat, bat, or cat Cat
[!a-z] matches one character that is not from the range given in the bracket Letter[!3-5] Letter1, Letter2, Letter6 up to Letter9 and Letterx etc. Letter3, Letter4, Letter5 or Letterxx

The ranges are also allowed to include pre-defined character classes, equivalence classes for accented characters, and collation symbols for hard-to-type characters. They are defined to match up with the brackets in POSIX regular expressions.[6][7]

Unix globbing is handled by the shell per POSIX tradition. Globbing is provided on filenames at the command line and in shell scripts.[8] The POSIX-mandated case statement in shells provides pattern-matching using glob patterns.

Some shells (such as the C shell and Bash) support additional syntax known as alternation or brace expansion. Because it is not part of the glob syntax, it is not provided in case. It is only expanded on the command line before globbing.

The Bash shell also supports the following extensions:[9]

  • Extended globbing (extglob): allows other pattern matching operators to be used to match multiple occurrences of a pattern enclosed in parentheses, essentially providing the missing kleene star and alternation for describing regular languages. It can be enabled by setting the extglob shell option. This option came from ksh93.[10] The GNU fnmatch and glob has an identical extension.[3]
  • globstar: allows ** on its own as a name component to recursively match any number of layers of non-hidden directories.[10] Also supported by the JS libraries and Python's glob.

Windows and DOS

The dir command with a glob pattern in IBM PC DOS 1.0.

The original DOS was a clone of CP/M designed to work on Intel's 8088 and 8086 processors. Windows shells, following DOS, do not traditionally perform any glob expansion in arguments passed to external programs. Shells may use an expansion for their own builtin commands:

  • Windows PowerShell has all the common syntax defined as stated above without any additions.[11]
  • COMMAND.COM and cmd.exe have most of the common syntax with some limitations: There is no […] and for COMMAND.COM the * may only appear at the end of the pattern. It can not appear in the middle of a pattern, except immediately preceding the filename extension separator dot.

Windows and DOS programs receive a long command-line string instead of argv-style parameters, and it is their responsibility to perform any splitting, quoting, or glob expansion. There is technically no fixed way of describing wildcards in programs since they are free to do what they wish. Two common glob expanders include:[12]

  • The Microsoft C Runtime (msvcrt) command-line expander, which only supports ? and *.[13] Both ReactOS (crt/misc/getargs.c) and Wine (msvcrt/data.c) contain a compatible open-source implementation of __getmainargs, the function operating under-the-hood, in their core CRT.
  • The Cygwin and MSYS dcrt0.cc command-line expander, which uses the unix-style glob() routine under-the-hood, after splitting the arguments.

Most other parts of Windows, including the Indexing Service, use the MS-DOS style of wildcards found in CMD. A relic of the 8.3 filename age, this syntax pays special attention to dots in the pattern and the text (filename). Internally this is done using three extra wildcard characters, <>". On the Windows API end, the glob() equivalent is FindFirstFile, and fnmatch() corresponds to its underlying RtlIsNameInExpression.[14] (Another fnmatch analogue is PathMatchSpec.) Both open-source msvcrt expanders use FindFirstFile, so 8.3 filename quirks will also apply in them.

SQL

The SQL LIKE operator has an equivalent to ? and * but not […].

Common wildcard SQL wildcard Description
? _ matches any single character
* % matches any number of any characters including none

Standard SQL uses a glob-like syntax for simple string matching in its LIKE operator, although the term "glob" is not generally used in the SQL community. The percent sign (%) matches zero or more characters and the underscore (_) matches exactly one.

Many implementations of SQL have extended the LIKE operator to allow a richer pattern-matching language, incorporating character ranges ([…]), their negation, and elements of regular expressions.[15]

Compared to regular expressions

Globs do not include syntax for the Kleene star which allows multiple repetitions of the preceding part of the expression; thus they are not considered regular expressions, which can describe the full set of regular languages over any given finite alphabet.[16]

Common wildcard Equivalent regular expression
? .
* .*

Globs attempt to match the entire string (for example, S*.DOC matches S.DOC and SA.DOC, but not POST.DOC or SURREY.DOCKS), whereas, depending on implementation details, regular expressions may match a substring.

Implementing as regular expressions

The original Mozilla proxy auto-config implementation, which provides a glob-matching function on strings, uses a replace-as-RegExp implementation as above. The bracket syntax happens to be covered by regex in such an example.

Python's fnmatch uses a more elaborate procedure to transform the pattern into a regular expression.[17]

Other implementations

Beyond their uses in shells, globs patterns also find use in a variety of programming languages, mainly to process human input. A glob-style interface for returning files or an fnmatch-style interface for matching strings are found in the following programming languages:

  • C# has multiple libraries available through NuGet such as Glob.[18] or DotNet.Glob.[19]
  • D has a globMatch function in the std.path module.[20]
  • JavaScript has a library called minimatch which is used internally by npm, and micromatch, a purportedly more optimized, accurate and safer globbing implementation used by Babel and yarn.[21][22]
  • Go has a Glob function in the filepath package.[23]
  • Java has a Files class containing methods that operate on glob patterns.[24]
  • Haskell has a Glob package with the main module System.FilePath.Glob. The pattern syntax is based on a subset of Zsh's. It tries to optimize the given pattern and should be noticeably faster than a naïve character-by-character matcher.[25]
  • Perl has both a glob function (as discussed in Larry Wall's book Programming Perl) and a Glob extension which mimics the BSD glob routine.[26] Perl's angle brackets can be used to glob as well: <*.log>.
  • PHP has a glob function.[27]
  • Python has a glob module in the standard library which performs wildcard pattern matching on filenames,[28] and an fnmatch module with functions for matching strings or filtering lists based on these same wildcard patterns.[17] Guido van Rossum, author of the Python programming language, wrote and contributed a glob routine to BSD Unix in 1986.[29] There were previous implementations of glob, e.g., in the ex and ftp programs in previous releases of BSD.
  • Ruby has a glob method for the Dir class which performs wildcard pattern matching on filenames.[30] Several libraries such as Rant and Rake provide a FileList class which has a glob method or use the method FileList.[] identically.
  • Rust has multiple libraries that can match glob patterns.[31]
  • SQLite has a GLOB function.
  • Tcl contains a globbing facility.[32]

See also

References

  1. "First Edition Unix manual 'Miscellaneous' section (PDF)". http://cm.bell-labs.com/cm/cs/who/dmr/man71.pdf. 
  2. Template:Cite tech report
  3. 3.0 3.1 fnmatch(3) – Linux Programmer's Manual – Library Functions
  4. glob(3) – Linux Programmer's Manual – Library Functions
  5. https://www.gnu.org/software/bash/manual/bash.html#Pattern-Matching Bash Reference Manual
  6. 6.0 6.1 "The Open Group Base Specifications Issue 7 IEEE Std 1003.1, 2013 Edition, 2.13. Pattern Matching Notation". http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_13. 
  7. 7.0 7.1 "Linux Programmer's Manual, GLOB(7)". http://man7.org/linux/man-pages/man7/glob.7.html. 
  8. The "Advanced Bash-Scripting Guide, Chapter 19.2: Globbing" (Mendel Cooper, 2003) has a concise set of examples of filename globbing patterns.
  9. "Bash globs". https://mywiki.wooledge.org/glob. 
  10. 10.0 10.1 "Pattern Matching". https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html. 
  11. "Supporting Wildcard Characters in Cmdlet Parameters". Microsoft Developer Network. https://docs.microsoft.com/en-us/powershell/developer/cmdlet/supporting-wildcard-characters-in-cmdlet-parameters. 
  12. "Wildcard Expansion". Microsoft Developer Network. 2013. http://msdn.microsoft.com/en-us/library/e1w828yy.aspx. 
  13. "Wildcard Expansion" (in en-us). https://docs.microsoft.com/en-us/cpp/cpp/wildcard-expansion. 
  14. Wildcards in Windows. MSDN Devblog.
  15. "LIKE (Transact-SQL)". https://docs.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql. 
  16. Hopcroft, John E.; Motwani, Rajeev; Ullman, Jeffrey D. (2000). Introduction to Automata Theory, Languages, and Computation (2nd ed.). Addison-Wesley. 
  17. 17.0 17.1 "Lib/fnmatch.py". Python. 20 January 2021. https://github.com/python/cpython/blob/3.8/Lib/fnmatch.py. 
  18. "kthompson/glob". https://github.com/kthompson/glob. 
  19. "dazinator/dotnet.glob". https://github.com/dazinator/DotNet.Glob. 
  20. "std.path - D Programming Language - Digital Mars". dlang.org. http://dlang.org/phobos/std_path.html#.globMatch. 
  21. "isaacs/minimatch". https://github.com/isaacs/minimatch. 
  22. "jonschlinkert/micromatch". https://github.com/jonschlinkert/micromatch. 
  23. "Package filepath - The Go Programming Language". Golang.org. http://golang.org/pkg/path/filepath/#Glob. 
  24. "File Operations". Oracle. http://docs.oracle.com/javase/tutorial/essential/io/fileOps.html#glob. 
  25. "Glob-0.7.4: Globbing library". http://hackage.haskell.org/package/Glob-0.7.4/docs/System-FilePath-Glob.html. 
  26. "File::Glob - Perl extension for BSD glob routine". perldoc.perl.org. http://perldoc.perl.org/File/Glob.html. 
  27. "glob - Manual". PHP. 2011-05-06. http://www.php.net/glob. 
  28. "10.7. glob — Unix style pathname pattern expansion — Python v2.7.1 documentation". Docs.python.org. https://docs.python.org/library/glob.html. 
  29. "'Globbing' library routine". http://www.isc.org/sources/devel/func/glob.txt. 
  30. "Class: Dir". Ruby-doc.org. http://www.ruby-doc.org/core/classes/Dir.html#M000629. 
  31. "#glob - Lib.rs". https://lib.rs/keywords/glob. 
  32. "TCL glob manual page". http://www.tcl.tk/man/tcl8.5/TclCmd/glob.htm.