Learning Wildcards for New Unix Users

Abstract: Teaches new Unix users to efficiently manage files using wildcard patterns like asterisks and question marks for commands such as ls, cp, and rm.

Created: 2026-09-01 by
Wildcards are essential Unix tools that allow you to match multiple filenames using special characters like asterisks and question marks. By leveraging these patterns in commands such as ls, cp, and rm, new users can efficiently manage large numbers of files without typing each name individually. This guide explains how to use globbing effectively to streamline your workflow and avoid common pitfalls.

Understanding Basic Wildcard Characters

In the Unix shell, wildcards are handled by a feature called "globbing." Before a command executes, the shell expands wildcard patterns into matching file names. The two most fundamental characters are the asterisk (*) and the question mark (?). Understanding their distinct behaviors is crucial for precise file manipulation.

The asterisk matches any sequence of characters, including zero characters. For example, *.txt will match all files ending with the extension .txt, regardless of what comes before it. This includes files named document.txt, report.txt, or even just .txt if hidden files are included in the search context. It is the most versatile tool for broad selection.

The question mark matches exactly one character. If you have files named file1.txt, file2.txt, and fileA.txt, the pattern file?.txt will match all three. However, it will not match file10.txt because the second position requires a single character, and 10 consists of two. This precision makes the question mark ideal when dealing with fixed-length naming conventions.

Practical Examples for File Management

Let us look at how these wildcards apply to everyday tasks. Suppose you want to list all directories in your current location. You can use the pattern */. The asterisk matches any filename, and the trailing slash ensures that only items identified as directories are returned. This is significantly faster than filtering the output of ls -l manually.

When copying files, wildcards save considerable time. To copy all image files from a folder to a backup directory, you would use: cp *.jpg /backup/images/. The shell expands *.jpg into every matching file name before passing them to the cp command. Note that if no files match the pattern, the shell might pass the literal string *.jpg to the command, which can cause errors. Always verify matches first using ls.

Renaming operations also benefit greatly from pattern matching. While mv itself does not support wildcards for bulk renaming in a single step (it moves one source to one destination), you can combine it with other tools. For instance, using a loop with for file in *.log; do ... done allows you to process each matched file individually. This approach is safer than trying to guess complex one-liners.

Handling Hidden Files

A common mistake for beginners is forgetting that standard wildcards do not match hidden files by default. In Unix, files starting with a dot (.) are considered hidden. Therefore, *.log will not match .secret.log. To include hidden files, you must explicitly add a pattern for them, such as *.log .*.log, or use shell options like nullglob if available in your specific shell environment.

Advanced Patterns and Safety Tips

Beyond simple characters, some shells support extended globbing. Bash, for example, allows features like ** to match files in subdirectories recursively when enabled via shopt -s globstar. This is powerful but dangerous if used carelessly. Always test your patterns with echo before executing destructive commands like rm.

# Safe way to preview what will be deleted
echo rm *.tmp

# Only delete if the preview looks correct
rm *.tmp

This practice prevents accidental data loss. Another useful tip is to quote your arguments when you intentionally want to prevent expansion. If you have a file literally named *.txt, using rm *.txt will try to delete all text files instead. Using rm "*.txt" forces the shell to treat the asterisk as a regular character.

For more complex file selection criteria, consider combining wildcards with tools like find. While find uses its own syntax for patterns, it offers greater control over permissions, modification times, and directory depth. For example, finding all writable text files older than a week requires more logic than simple globbing can provide.

Common Pitfalls to Avoid

One frequent issue is the "argument list too long" error. When a wildcard matches thousands of files, the resulting command line may exceed the system's argument limit. In such cases, using xargs is the solution. It breaks the input into smaller chunks, allowing commands to process large sets of files safely.

Another pitfall involves spaces in filenames. Wildcards expand to full paths, so if a file contains spaces, unquoted expansions can break commands. For example, cp *.dat /dest/ works fine, but processing those files in a script requires careful quoting to ensure each filename is treated as a single unit. Using find ... -print0 and xargs -0 is the robust method for handling arbitrary filenames.

Finally, remember that wildcards are expanded by the shell, not the command itself. This means the command never sees the wildcard characters; it only sees the list of matched files. This distinction is important for debugging why a command behaves unexpectedly with certain inputs.

Frequently Asked Questions

Do wildcards work in Windows Command Prompt?

Yes, but the syntax differs slightly. Windows uses * and ? similarly, but it lacks the recursive ** feature found in modern Unix shells unless you use PowerShell. Additionally, Windows handles case sensitivity differently, whereas Unix wildcards are typically case-sensitive.

How can I match files that start with a number?

You can use character classes within brackets. For example, [0-9]*.txt matches any text file whose name begins with a digit. This bracket notation allows you to specify a range of characters or a specific set, providing much finer control than simple asterisks.

Why did my rm command fail with "No such file or directory"?

This usually happens when the wildcard pattern matches nothing. The shell passes the literal pattern string to rm, which then tries to delete a file named exactly like the pattern. To fix this, enable nullglob in bash or check your pattern against existing files using ls first.

Can I use wildcards with grep?

Not directly in the same way. grep uses Regular Expressions (regex) for searching content, while wildcards are for filename matching. However, you can combine them by using wildcards to select files and grep to search inside them, like grep "pattern" *.log.

What is the difference between * and ** in Bash?

The single asterisk * matches files in the current directory only. The double asterisk **, when enabled with globstar, matches files in the current directory and all subdirectories recursively. This makes it easier to find files deep in a directory tree without specifying every intermediate folder.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More