Advanced Bash Scripting
Globs
Mixed
In this lesson, we’ll take your globbing skills to the next level by combining ?
, *
, and escape sequences to match complex filename patterns. Glob patterns allow you to filter filenames efficiently without resorting to regular expressions.
Note
For an in-depth reference on Bash filename expansion, see Bash Pattern Matching.
Below is a quick summary of common glob operators:
Wildcard | Description | Example |
---|---|---|
* | Matches zero or more characters | *.txt |
? | Matches exactly one character | file.? |
\ | Escapes the next character literally | file\*.* |
Workflow for Building Complex Globs
Sample Selection
Collect filenames and mark matches (✅) vs. non-matches (❌). Identify blue segments (literal text) and yellow segments (wildcards).Category Order
Note the sequence of blue and yellow segments in the target filenames.Construct the Glob
Concatenate literals and wildcards in the order you determined.
Example 1: Match “file.” plus at Least One Character
Samples
file. ❌
file.c ✅
file.conf ✅
file.txt ✅
data.sh ❌
- Blue:
file.
- Yellow:
?
(one char) then*
(rest) - Glob:
file.?*
$ ls file.?*
file.c file.conf file.txt
Example 2: Match “file_” Prefix and a Three-Character Extension
Samples
file_1.txt ✅
file_2.doc ✅
file_1_a.sh ❌
file_2_b.doc ✅
- Blue:
file_
- Yellow:
*
(any chars before dot) - Blue:
.
- Yellow:
???
(exactly three) - Glob:
file_*.___
$ ls file_*.___
file_1.txt file_2.doc file_2_b.doc
Example 3: Match Any Name with a Four-Character Extension
Samples
document1.txt ❌
image1.py ❌
report2.pdf ❌
memo1.docx ✅
invoice3.xlsx ✅
- Yellow:
*
(any prefix) - Blue:
.
- Yellow:
????
(exactly four) - Glob:
*.????
$ ls *.????
memo1.docx invoice3.xlsx
Example 4: Match Names Containing “1” Then One More Character, Then an Extension
Samples
file1.sh ❌
document1M.docx ✅
file3.txt ❌
image1T.png ✅
- Yellow:
*
(any prefix) - Blue:
1
- Yellow:
?
(one char) - Blue:
.
- Yellow:
*
(any extension) - Glob:
*1?.*
$ ls *1?.*
document1M.docx image1T.png
Example 5: Escaping a Literal “*” in Filenames
Samples
R*al.py ✅
f*a*il.txt ✅
hail.doc ❌
S*ail.txt ✅
m*a?i*l.sh ✅
4ai*l.txt ❌
- Yellow:
?
(any single) - Blue:
\*
(escaped*
) - Blue:
a
- Yellow:
*
- Blue:
.
- Yellow:
*
- Glob:
?\*a*.*
Warning
Be sure to quote or escape the pattern in your shell to prevent expansion before ls
sees it.
$ ls '?\*a*.*'
R*al.py f*a*il.txt S*ail.txt m*a?i*l.sh
Example 6: Escaping a Backslash and Question Mark
Samples
file5\?xt ✅
file_1234567\?890?xt ✅
docA\?.docx ✅
docZ.docx ❌
rep1.txt ❌
- Yellow:
*
(any prefix) - Blue:
\\?
(escaped\?
) - Yellow:
*
(any remainder) - Glob:
*\\?*
$ ls '*\\?*'
file5\?xt file_1234567\?890?xt docA\?.docx
Conclusion
By splitting filenames into literal (blue) and wildcard (yellow) segments, you can craft precise glob patterns for matching even the trickiest file names.
Links and References
Watch Video
Watch video content