Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 14

File Globbing and Wildcards for Batch Operations

Recommended resources

Hello! Welcome to your next lesson in the "Command Line and File System Navigation" module.

In our last session, you learned the essential commands for managing individual files and directories: mkdir, touch, cp, mv, and rm. This gave you precise control over single items in your filesystem.

Today, we're going to significantly upgrade your command-line efficiency. This lesson focuses on using file globbing patterns and wildcards to perform batch operations. Instead of copying or deleting files one by one, you'll learn how to target dozens or even hundreds of files with a single, elegant command. This skill is a cornerstone of proficient Linux use and is crucial for the CompTIA Linux+ exam.

1. What is File Globbing?

Before we dive into the wildcards themselves, it's important to understand what is happening when you use them. The term "globbing" refers to the process where the shell—your command-line interpreter (like Bash)—finds all filenames that match a specific pattern and expands that pattern into a list of files before the command is even run.

For example, when you type rm *.log, the rm command itself never sees the asterisk. The shell first finds all files in the current directory ending in .log (e.g., app.log, system.log, error.log) and then effectively runs the command rm app.log system.log error.log.

This concept is key to understanding how globbing works. Let's watch a short video that explains this process.

What The GLOB?! Filename Expansion in Linux 📦

This video from NIX tricks introduces the concept of 'globbing' or 'filename expansion'. It explains what it is and clarifies that the shell is responsible for expanding the patterns.

Watch the first 1 minute and 24 seconds. The main takeaway is that the shell expands wildcard patterns into a list of matching filenames before your command is executed.


2. The Core Wildcards

There are three primary wildcard patterns you will use constantly. Let's explore each one.

The Asterisk (*): Matches Any Number of Characters

The asterisk is the most versatile and common wildcard. It matches any sequence of characters, including zero characters.

  • *.txt: Matches all files ending in .txt.
  • report_*: Matches all files starting with report_.
  • *draft*: Matches all files with "draft" anywhere in their name.

The following video from DistroTube gives a clear, practical demonstration using the rm command, which directly builds on our last lesson.

File Globbing In Linux

This segment demonstrates the * wildcard, showing how it can be used to perform an operation on multiple files at once.

Watch from 00:49 to 01:59. Notice how rm *.txt is a far more efficient way to remove all text files than listing each one individually.

Linux Terminal Demonstrating File Globbing with Asterisk Wildcard
This terminal screenshot demonstrates several `rm` commands using the `*` wildcard to delete files in batches.

The Question Mark (?): Matches Exactly One Character

When you need more precision, the question mark is your tool. It matches exactly one of any character. This is useful for matching files that have a similar naming pattern but differ by a single character.

  • report_v?.doc: Matches report_v1.doc and report_vA.doc, but not report_v10.doc.
  • log_??.txt: Matches log_01.txt and log_ab.txt, but not log_1.txt or log_123.txt.

Let's continue with the same video, as it flows directly into explaining the question mark.

File Globbing In Linux

Now, let's look at the question mark (?). This segment clearly illustrates how it differs from the asterisk by matching only a single character.

Watch from 01:59 to 03:05. The key concept here is understanding why file?.txt does not match file10.txt.

Square Brackets ([]): Matching a Set of Characters

For the most specific matching, you can use square brackets to define a set of characters or a range. A pattern with [] will match any single character that is part of the specified set.

  • Character List: [abc] matches a, b, or c.
    • Example: image_[abc].jpg matches image_a.jpg, image_b.jpg, or image_c.jpg.
  • Character Range: [0-9] matches any single digit. [a-z] matches any single lowercase letter.
    • Example: file[1-3].log matches file1.log, file2.log, and file3.log.
  • Negation: Placing an exclamation mark ! or a caret ^ as the first character inside the brackets negates the set. It matches any character not in the set.
    • Example: file[!1-3].log matches file4.log and fileA.log, but not file1.log, file2.log, or file3.log.

The following video segments demonstrate both creating character sets and negating them.

File Globbing In Linux

To see how to use brackets for character sets, ranges, and negation, watch these next two clips.

Watch from 03:05 to 06:08. First, focus on how [0-9] and custom sets work. Then, pay attention to how the ! inverts the logic to exclude characters.

Linux Terminal Demonstrating File Globbing with Character Ranges and Question Mark Wildcard
This example shows the command `ls b-[12]?.txt`. The `[12]` matches files containing either a '1' or a '2', and the `?` matches any single character that follows, effectively selecting files like `b-10.txt` and `b-20.txt`.
Test your understanding!

You have a directory containing the following files:
report_final.docx, report_jan.pdf, report_feb.pdf, report_mar.pdf, report_1.txt, report_10.txt, template.txt

Which ls command with a globbing pattern would you use to list only report_jan.pdf and report_feb.pdf?

  1. ls report_???.pdf
  2. ls report_[jf]*.pdf
  3. ls report_*.pdf
  4. ls report_[!mar].pdf
Show answer

The correct answer is 2. ls report_[jf]*.pdf.

Let's break down why:

  • report_: Matches the literal text.
  • [jf]*: This is a bit tricky. The correct pattern would be report_[jf]*.pdf. A better pattern is ls report_[j,f]??.pdf or ls report_j??.pdf report_f??.pdf. Let's assume the question meant ls report_[jf]??.pdf. That would match j or f followed by two characters.
    Let's analyze the provided options more carefully. ls report_[jf]*.pdf would actually match report_jan.pdf, report_feb.pdf, and also report_final.docx if it were a .pdf. The question implies we want only those two files.

A better answer would be ls report_[jf]??.pdf. Let's re-evaluate the options given the file list.

  1. ls report_???.pdf: This would list report_jan.pdf, report_feb.pdf, and report_mar.pdf (all have 3 characters after the underscore).
  2. ls report_[jf]*.pdf: This would list report_jan.pdf and report_feb.pdf. It's the best fit among the choices. It wouldn't match report_mar.pdf.
  3. ls report_*.pdf: This would list report_jan.pdf, report_feb.pdf, and report_mar.pdf.
  4. ls report_[!mar].pdf: This syntax is incorrect. It would try to match any character except m, a, or r. It would match report_jan.pdf (since 'j' is not in mar) but would fail unexpectedly on report_feb.pdf (since 'e' is not in mar but 'f' is). A correct negation would be ls report_[!m]??.pdf, which would exclude mar but still include jan and feb.

Therefore, option 2 is the most precise choice among the flawed options to select just the January and February reports.


3. Practical Use and Common Pitfalls

Knowing the wildcards is one thing; using them safely and effectively is another. A common point of confusion for newcomers is trying to rename a batch of files.

For example, you might think you can rename all .html files to .php with mv *.html *.php. This will not work as you expect. The shell expands *.html into a list of files, but if no files ending in .php exist, *.php remains a literal string. The mv command then tries to move all your HTML files into a non-existent directory named *.php, which results in an error.

This is a classic exam-style question. The following reading from a Linux+ certification guide explains this pitfall clearly.

CompTIA® Linux+ / LPIC-1 Cert Guide

This excerpt from the 'CompTIA® Linux+ / LPIC-1 Cert Guide' explains how the shell is responsible for glob expansion and demonstrates the common error when trying to batch-rename files.

Read the section titled 'Determining File Types'. Start from the 'NOTE' that begins 'The asterisk (*) in the previous command is known as a glob' and continue to the end of 'Example 5-1'. Focus on the explanation and output for the mv *.foo *.bar command.

Safe Practice: When you're about to perform a destructive operation like rm or mv with a wildcard, it's a very good habit to test your pattern with ls or echo first.

  • echo rm *.tmp
  • ls *.tmp

This will show you the list of files that your wildcard pattern matches before you actually delete or move them.


4. A Glimpse into Advanced Globbing

The basic wildcards will handle 95% of your needs. However, it's good to be aware that most modern shells, including Bash, offer more advanced globbing features that you can enable. You don't need to master these now, but knowing they exist is valuable.

  • globstar (**): When enabled, the double-asterisk ** matches files and directories recursively. For example, ls **/*.log would find every .log file in the current directory and all subdirectories, no matter how deep.
  • extglob (Extended Globbing): This enables more complex patterns, such as matching one of several complete patterns (e.g., *.@(jpg|jpeg|png)) or excluding a pattern (e.g., !(*.txt)).

This video gives a quick tour of these powerful features.

What The GLOB?! Filename Expansion in Linux 📦

To see what's possible beyond the basics, this segment introduces advanced shell options like globstar for recursive searching and extglob for complex patterns.

Watch from 05:47 to 08:11. You don't need to memorize the syntax. Just absorb the concepts of what globstar and extglob allow you to do, especially excluding files and recursive searching.


Conclusion

You've now added a powerful tool to your command-line arsenal. By mastering globbing, you've moved from manipulating single files to managing entire sets of files with ease and efficiency.

Key Takeaways:

  • Globbing is a Shell Feature: The shell expands patterns like *.txt into a file list before the command runs.
  • Core Wildcards:
    • *: Matches any number of characters (zero or more).
    • ?: Matches exactly one character.
    • []: Matches one character from a specific set or range (e.g., [a-z], [1-5], [aeiou]).
    • [!...]: Matches any character not in the set.
  • Practice Safely: Always test a complex or destructive wildcard pattern with echo or ls before executing it with rm or mv.
  • Common Pitfall: You cannot use a simple mv *.old *.new to rename files. This requires more advanced methods like shell loops, which we will cover later in the course.

In our next lesson, we'll shift our focus from managing files to inspecting them. You'll learn how to view the contents of text files directly in your terminal using fundamental commands like cat, less, head, and tail.