Wildcards: Working with Many Files

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.

WildcardMatchesExample
*Any number of any characters (even none)*.jpg: every name ending in .jpg
?Exactly one characterimg?.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 rangeimg[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 pictures

In 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 *.txt

In 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
ls

In 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 not rm *.txt. The first deletes every file, then complains that .txt doesn't exist.

Remember: * any characters, ? one character, [ ] one of a set. Preview with echo or ls first.

HOME LEARN COMMUNITY DASHBOARD
Practice terminal Starting…