0
0
Linux CLIscripting~5 mins

File globbing (wildcards *, ?, []) in Linux CLI - Commands & Configuration

Choose your learning style9 modes available
Introduction
File globbing helps you find or work with groups of files using simple patterns instead of typing every file name. It saves time when you want to list, copy, or delete many files that share similar names.
When you want to list all files with a certain extension, like all .txt files in a folder.
When you need to copy all images starting with 'photo' to another folder.
When you want to delete all backup files ending with ~ in a directory.
When you want to check the contents of files that start with a specific letter.
When you want to move files with names matching a pattern but don’t want to type each name.
Commands
Lists all files in the current directory that end with .txt using the * wildcard to match any characters before .txt.
Terminal
ls *.txt
Expected OutputExpected
notes.txt report.txt todo.txt
Lists files with names starting with 'photo' followed by exactly one character, then .jpg. The ? matches any single character.
Terminal
ls photo?.jpg
Expected OutputExpected
photo1.jpg photoA.jpg
Lists files named file1.log, file2.log, or file3.log. The [123] matches any one character inside the brackets.
Terminal
ls file[123].log
Expected OutputExpected
file1.log file2.log file3.log
Deletes all files starting with 'backup~' followed by any characters. Useful for removing backup files with names like backup~1, backup~old.
Terminal
rm backup~*
Expected OutputExpected
No output (command runs silently)
Copies files with names like report1.doc or reportA.doc to the documents folder. The ? matches exactly one character.
Terminal
cp report?.doc /home/user/documents/
Expected OutputExpected
No output (command runs silently)
Key Concept

If you remember nothing else from this pattern, remember: * matches any number of characters, ? matches exactly one character, and [ ] matches any one character inside the brackets.

Common Mistakes
Using * when you mean to match exactly one character.
* matches zero or more characters, so it can match more files than intended.
Use ? to match exactly one character when you want precise control.
Forgetting to quote patterns when files have spaces.
Shell splits unquoted patterns on spaces, causing errors or unexpected matches.
Put quotes around patterns like "*.txt" if filenames may contain spaces.
Using [ ] with ranges incorrectly, like [1-3a].
Ranges must be continuous; mixing numbers and letters without proper syntax causes no matches.
Use separate ranges or list characters explicitly, e.g., [1-3a] is valid but be sure what you want to match.
Summary
Use * to match any number of characters in file names.
Use ? to match exactly one character in file names.
Use [ ] to match any one character from a set or range.
Combine these wildcards to select groups of files quickly.
Always check your matches with ls before running commands that change files.