Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

glob (programming)

From Wikipedia, the free encyclopedia
Patterns used in computer programming

A screenshot of the original 1971 Unix reference page forglob – the owner isdmr, short forDennis MacAlistair Ritchie.

glob() (/ɡlɒb/) is alibc function forglobbing, which is the archetypal use of pattern matching against thenames in a filesystem directory such that a name pattern is expanded into a list of names matching that pattern. Althoughglobbing may now refer toglob()-style pattern matching of any string, not just expansion into a list of filesystem names, the original meaning of the term is still widespread.

Theglob() function and the underlyinggmatch() function originated atBell Labs in the early 1970s alongside the originalAT&T UNIX itself and had a formative influence on the syntax of UNIX command line utilities and therefore also on the present-day reimplementations thereof.

In their original form,glob() andgmatch() derived from code used inBell Labs in-house utilities that developed alongside the original Unix in the early 1970s. Among those utilities were also two command line tools calledglob andfind; each could be used to pass a list of matching filenames to other command line tools, and they shared the backend code subsequently formalized asglob() andgmatch(). Shell-statement-level globbing by default became commonplace following the"builtin"-integration of globbing-functionality into the7th edition of theUnix shell in 1978. The Unix shell's -f option to disable globbing — i.e. revert to literal "file" mode — appeared in the same version.

The globpattern quantifiers now standardized byPOSIX.2 (IEEE Std 1003.2) fall into two groups, and can be applied to any character sequence ("string"), not just to directory entries.

  • "Metacharacters" (also called "Wildcards"):
    • ? (not in brackets) matches any character exactly once.
    • * (not in brackets) matches a string of zero or more characters.
  • "Ranges/sets":
    • [...], where the first character within the brackets is not '!', matches any single character among the characters specified in the brackets. If the first character within brackets is '!', then the[!...] matches any single character that isnot among the characters specified in the brackets.
The characters in the brackets may be a list ([abc]) or a range ([a-c]) or denote a character class (like[[:space:]] where the inner brackets are part of the classname). POSIX does not mandate multi-range ([a-c0-3]) support, which derive originally fromregular expressions.

As reimplementations ofBell Labs' UNIX proliferated, so did reimplementations of its Bell Labs' libc and shell, and with themglob() andglobbing. Today,glob() andglobbing are standardized by thePOSIX.2 specification and are integral part of every Unix-like libc ecosystem and shell, including AT&T Bourne shell-compatibleKorn shell (ksh),Z shell (zsh),Almquist shell (ash) and its derivatives and reimplementations such asbusybox,toybox,GNU bash,Debian dash.

Origin

[edit]

The glob command, short forglobal, 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 expandwildcard 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 theB programming language. It was the first piece of mainline Unix software to be developed in ahigh-level programming language.[2] Later, this functionality was provided as a Clibrary function,glob(), used by programs such as theshell. It is usually defined based on a function namedfnmatch(), 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 ofPOSIX: 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 withwildmat (wildcard match), a simple library to match strings against Bourne Shell globs.

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

Syntax

[edit]

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

WildcardDescriptionExampleMatchesDoes not match
*matches any number of any characters including noneLaw*Law,Laws, orLawyerGrokLaw,La, oraw
*Law*Law,GrokLaw, orLawyer.La, oraw
?matches any single character?atCat,cat,Bat orbatat
[abc]matches one character given in the bracket[CB]atCat orBatcat,bat orCBat
[a-z]matches one character from the (locale-dependent) range given in the bracketLetter[0-9]Letter0,Letter1,Letter2 up toLetter9Letters,Letter orLetter10

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

Unix-like

[edit]

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

WildcardDescriptionExampleMatchesDoes not match
[!abc]matches one character that is not given in the bracket[!C]atBat,bat, orcatCat
[!a-z]matches one character that is not from the range given in the bracketLetter[!3-5]Letter1,Letter2,Letter6 up toLetter9 andLetterx etc.Letter3,Letter4,Letter5 orLetterxx

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 theshell per POSIX tradition. Globbing is provided on filenames at thecommand line and inshell scripts.[8] The POSIX-mandatedcase statement in shells provides pattern-matching using glob patterns.

Some shells (such as theC shell andBash) support additional syntax known asalternation orbrace expansion. Because it is not part of the glob syntax, it is not provided incase. 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 missingkleene star and alternation for describing regular languages. It can be enabled by setting theextglob 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 theJavaScript libraries andPython's glob.

Windows and DOS

[edit]
Thedir command with a glob pattern inIBM PC DOS 1.0.

The originalDOS was a clone ofCP/M designed to work on Intel's8088 and8086 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 andcmd.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 thefilename 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] BothReactOS (crt/misc/getargs.c) andWine (msvcrt/data.c) contain a compatible open-source implementation of__getmainargs, the function operating under-the-hood, in their core CRT.
  • TheCygwin and MSYSdcrt0.cc command-line expander, which uses the unix-styleglob() 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, theglob() equivalent isFindFirstFile, andfnmatch() corresponds to its underlyingRtlIsNameInExpression.[14] (Another fnmatch analogue isPathMatchSpec.) Both open-source msvcrt expanders useFindFirstFile, so 8.3 filename quirks will also apply in them.

SQL

[edit]

TheSQLLIKE operator has an equivalent to? and* but not[…].

Common wildcardSQL wildcardDescription
?_matches any single character
*%matches any number of any characters including none

Standard SQL uses a glob-like syntax for simple string matching in itsLIKE 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 theLIKE operator to allow a richer pattern-matching language, incorporating character ranges ([…]), their negation, and elements of regular expressions.[15]

Compared to regular expressions

[edit]

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

Common wildcardEquivalent 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

[edit]

The original Mozillaproxy 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

[edit]

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 andC++ do not have built-in support for glob patterns in the ISO-defined standard libraries, however on Unix-like systems C and C++ may include<glob.h> from theC POSIX library to use::glob().
    • C++ itself does not have direct support for glob patterns, however they may be approximated using the<filesystem> and<regex> headers, usingstd::filesystem::directory_iterator andstd::regex_match().
    • C++ has external libraries, such asPOCO C++ Libraries, which includes aGlob class which can act on glob patterns.[18]
  • C# provides the official extension libraryMicrosoft.Extensions.FileSystemGlobbing[19], which contains classMatcher.[20]
    • C# also has multiple external libraries available throughNuGet such asGlob[21] orDotNet.Glob.[22]
  • D has aglobMatch function in thestd.path module.[23]
  • Go has aGlob function in thefilepath package.[24]
  • Java provides packagejava.nio.file which contains classFiles[25], which has methods such asFiles.newDirectoryStream(Pathdir,Stringglob) for operating over glob patterns and returnsDirectoryStream<Path>. The package also contains the classesFileSystems andPathMatcher for matching glob patterns.
  • Haskell has aGlob package with the main moduleSystem.FilePath.Glob. The pattern syntax is based on a subset ofZsh's. It tries to optimize the given pattern and should be noticeably faster than a naïve character-by-character matcher.[26]
  • Node.js has aglob function in thenode:fs module.[27]
  • Perl has both aglob function (as discussed inLarry Wall's bookProgramming Perl) and aGlob extension which mimics the BSD glob routine.[28] Perl's angle brackets can be used to glob as well:<*.log>.
  • PHP has aglob function.[29]
  • Python has aglob module in the standard library which performs wildcard pattern matching on filenames,[30] and anfnmatch 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 aglob routine toBSDUnix in 1986.[31] There were previous implementations ofglob, e.g., in theex andftp programs in previous releases of BSD.
  • Ruby has aglob method for theDir class which performs wildcard pattern matching on filenames.[32] Several libraries such as Rant and Rake provide aFileList class which has a glob method or use the methodFileList.[] identically.
  • Rust has multiple libraries that can match glob patterns,[33] the most popular of these being theglob crate which itself has aglob() function.[34]
  • SQLite has aGLOB function.
  • Tcl contains a globbing facility.[35]

See also

[edit]

References

[edit]
  1. ^"First Edition Unix manual 'Miscellaneous' section (PDF)"(PDF). Archived fromthe original(PDF) on 2000-08-29. Retrieved2011-05-11.
  2. ^McIlroy, M. D. (1987).A Research Unix reader: annotated excerpts from the Programmer's Manual, 1971–1986(PDF) (Technical report). CSTR. Bell Labs. 139.
  3. ^abfnmatch(3) – Linux Programmer'sManual – Library Functions from Manned.org
  4. ^glob(3) – Linux Programmer'sManual – Library Functions from Manned.org
  5. ^https://www.gnu.org/software/bash/manual/bash.html#Pattern-MatchingArchived 2018-03-15 at theWayback Machine Bash Reference Manual
  6. ^ab"The Open Group Base Specifications Issue 7 IEEE Std 1003.1, 2013 Edition, 2.13. Pattern Matching Notation".Archived from the original on 2014-04-27. Retrieved2015-10-26.
  7. ^ab"Linux Programmer's Manual, GLOB(7)".Archived from the original on 2015-10-31. Retrieved2015-10-26.
  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".greg's bash knowledgebase.Archived from the original on 2019-11-18. Retrieved2019-11-25.
  10. ^ab"Pattern Matching".Bash Reference Manual.Archived from the original on 2016-02-11. Retrieved2016-01-11.
  11. ^"Supporting Wildcard Characters in Cmdlet Parameters".Microsoft. Microsoft Developer Network. 2023-12-18.
  12. ^"Wildcard Expansion". Microsoft Developer Network. 2013.Archived from the original on 2014-08-22. Retrieved2013-10-16.
  13. ^"Wildcard Expansion".docs.microsoft.com. 2022-02-08.
  14. ^Wildcards in WindowsArchived 2019-12-24 at theWayback Machine. MSDN Devblog.
  15. ^"LIKE (Transact-SQL)". 2023-05-23.Archived from the original on 2017-08-02. Retrieved2017-08-01.
  16. ^Hopcroft, John E.; Motwani, Rajeev; Ullman, Jeffrey D. (2000).Introduction to Automata Theory, Languages, and Computation (2nd ed.). Addison-Wesley.
  17. ^ab"Lib/fnmatch.py". Python. 2021-01-20.Archived from the original on 2021-11-10. Retrieved2021-11-10.
  18. ^"Class Poco::Glob".docs.pocoproject.org. Retrieved2025-08-13.
  19. ^"NuGet Gallery Microsoft.Extensions.FileSystemGlobbing".www.nuget.org. Retrieved2025-08-17.
  20. ^"File globbing in .NET".learn.microsoft.com. Retrieved2025-08-17.
  21. ^"kthompson/glob".GitHub.Archived from the original on 2020-10-26. Retrieved2020-11-06.
  22. ^"dazinator/dotnet.glob".GitHub.Archived from the original on 2022-06-22. Retrieved2022-06-22.
  23. ^"std.path - D Programming Language - Digital Mars". dlang.org.Archived from the original on 2014-09-08. Retrieved2014-09-08.
  24. ^"Package filepath - The Go Programming Language". Golang.org.Archived from the original on 2011-05-25. Retrieved2011-05-11.
  25. ^"File Operations". Oracle.Archived from the original on 2013-09-20. Retrieved2013-12-16.
  26. ^"Glob-0.7.4: Globbing library".Archived from the original on 2014-05-08. Retrieved2014-05-07.
  27. ^"File system - Node.js Documentation".Archived from the original on 2025-07-16. Retrieved2025-07-16.
  28. ^"File::Glob - Perl extension for BSD glob routine". perldoc.perl.org. Retrieved2011-05-11.
  29. ^"glob - Manual". PHP. 2011-05-06.Archived from the original on 2017-11-13. Retrieved2011-05-11.
  30. ^"10.7. glob — Unix style pathname pattern expansion — Python v2.7.1 documentation". Docs.python.org.Archived from the original on 2011-05-16. Retrieved2011-05-11.
  31. ^"'Globbing' library routine". Archived fromthe original on 2007-12-19. Retrieved2011-05-11.
  32. ^"Class: Dir". Ruby-doc.org.Archived from the original on 2011-05-15. Retrieved2011-05-11.
  33. ^"#glob - Lib.rs".lib.rs.Archived from the original on 2021-11-12. Retrieved2021-11-12.
  34. ^"glob - Lib.rs".lib.rs. Retrieved2025-01-17.
  35. ^"TCL glob manual page".Archived from the original on 2011-12-08. Retrieved2011-11-16.
Retrieved from "https://en.wikipedia.org/w/index.php?title=Glob_(programming)&oldid=1310246110"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2025 Movatter.jp