Wildcards are special characters used in Linux to represent unknown or variable values in filenames and commands. They allow users to efficiently search for, list, and manipulate multiple files at once without having to type each name explicitly. Wildcards are primarily used in conjunction with commands like ls, cp, mv, and rm, making file management more efficient.
The asterisk (*) is the most commonly used wildcard in Linux. It represents zero or more characters in a filename or directory. This means that it can match multiple files at once, regardless of the characters in their names.
-
Example:
ls *.txtThis command lists all files in the current directory that end with
.txt. -
Another Example:
rm file*This removes all files that start with "file", such as
file1.txt,file2.txt, orfile_document.txt.
The question mark (?) is used when a single character in a filename is unknown or variable. It matches exactly one character, making it useful for filtering files with slight differences in their names.
- Example:
This lists files like
ls file?.txtfile1.txt,fileA.txt, andfileB.txtbut notfile12.txtbecause?only replaces a single character.
Square brackets ([]) allow users to specify a set of possible characters to match in a filename. It replaces exactly one character but only with characters listed inside the brackets.
-
Example:
ls file[123].txt
This matches
file1.txt,file2.txt, andfile3.txtbut notfile4.txt. -
Range Example:
ls file[a-c].txt
This matches
filea.txt,fileb.txt, andfilec.txtbut notfiled.txt.
By adding an exclamation mark (!) or caret (^) inside square brackets, users can exclude certain characters instead of including them.
- Example:
This matches any
ls file[!123].txtfileX.txtwhereXis not1,2, or3.
Curly braces ({}) are not traditional wildcards but are used for brace expansion, allowing users to specify multiple options at once.
-
Example:
echo {file1,file2,file3}.txtThis expands to
file1.txt file2.txt file3.txt. -
Range Example:
echo {1..5}This expands to
1 2 3 4 5.
In newer versions of Bash (4.0+), enabling globstar allows the use of **, which searches recursively through directories.
- Example:
This lists all
shopt -s globstar # Enable globstar if not already enabled ls **/*.txt
.txtfiles in the current directory and all its subdirectories.