What are wildcards?
Wildcards (also called globs) are special characters that match file names. The shell replaces the pattern with every matching name before the command runs.
| Wildcard | Matches | Example |
|---|---|---|
* | Any number of any characters (even none) | *.jpg: every name ending in .jpg |
? | Exactly one character | img?.jpg: img1.jpg, but not img10.jpg |
[abc] | One of the characters in the brackets | [cd]*: names starting with c or d |
[0-9] | One character in the range | img[0-9].jpg |
Trying them out
ls
ls *.jpg
ls img?.jpg
ls [cd]*In the terminal
student@vulntech:~$ ls beach.jpg dog.png img10.jpg list.txt party.jpg cat.png img1.jpg img2.jpg notes.txt sunset.jpg student@vulntech:~$ ls *.jpg beach.jpg img1.jpg img10.jpg img2.jpg party.jpg sunset.jpg student@vulntech:~$ ls img?.jpg img1.jpg img2.jpg student@vulntech:~$ ls [cd]* cat.png dog.png
Wildcards work with every command
Because the shell expands them, wildcards work with cp, mv, rm and any other command:
mkdir pictures
mv *.png pictures/
ls picturesIn the terminal
student@vulntech:~$ mkdir pictures student@vulntech:~$ mv *.png pictures/ student@vulntech:~$ ls pictures cat.png dog.png
Preview with echo
echo shows what a pattern expands to without doing anything. Use it before a risky rm:
echo *.txtIn the terminal
student@vulntech:~$ echo *.txt list.txt notes.txt
Braces: making names
Braces are different: they don't match existing files, they generate words. They're great for creating many files or directories:
echo file{1,2,3}.txt
mkdir -p site/{css,js,images}
ls site
touch day{1..5}.log
lsIn the terminal
student@vulntech:~$ echo file{1,2,3}.txt file1.txt file2.txt file3.txt student@vulntech:~$ mkdir -p site/{css,js,images} student@vulntech:~$ ls site css images js student@vulntech:~$ touch day{1..5}.log student@vulntech:~$ ls day1.log day2.log day3.log day4.log day5.log site
Common mistake:
rm * .txt(with a space) is notrm *.txt. The first deletes every file, then complains that.txtdoesn't exist.
Remember:
*any characters,?one character,[ ]one of a set. Preview withechoorlsfirst.