Linux makes use of several wildcards, or characters that can be used to target multiple files. These wildcards are interpreted by the shell and the results are returned to the command you run. There are three main wildcards in Linux:
- An asterisk
*– matches one or more occurrences of any character, including no character.
- A question mark
?– represents or matches a single occurrence of any character.
- Bracketed characters
[ ]– matches any occurrence of character enclosed in the square brackets. It is possible to use different types of characters (alphanumeric characters): numbers, letters, other special characters etc.
You need to carefully choose which wildcard to use to match correct filenames: it is also possible to combine all of them in one operation as explained in the examples below.
How to Match Filenames Using Wildcards in Linux
For this article we will be querying an example directory containing these files:
createbackup.sh listopen.sh lspace.sh speaker.sh list.sh lost.sh rename-files.sh topprocs.sh
Using an asterisk
This command matches all files with names starting with
l (which is the prefix) and ending with one or more occurrences of any character.
ls -l l*
-rw-r--r-- 1 simonbrowne staff 0 Dec 7 15:46 list.sh -rw-r--r-- 1 simonbrowne staff 0 Dec 7 15:46 listopen.sh -rw-r--r-- 1 simonbrowne staff 0 Dec 7 15:46 lost.sh -rw-r--r-- 1 simonbrowne staff 0 Dec 7 15:46 lspace.sh
Using a question mark
The following command matches all files with names beginning with
l followed by any single character and ending with
st.sh (which is the suffix):
Using square brackets
The command below matches all files with names starting with
l followed by any of the characters in the square bracket but ending with
How to Combine Wildcards to Match Filenames in Linux
You can combine wildcards to build a complex filename matching criteria as described in the following examples.
1. This command will match all filenames prefixed with any two characters followed by st but ending with one or more occurrence of any character.
list.sh listopen.sh lost.sh
2. This example matches filenames starting with any of these characters [clst] and ending with one or more occurrence of any character.
createbackup.sh listopen.sh lspace.sh topprocs.sh list.sh lost.sh speaker.sh