Wildcards (also referred to as meta characters) are symbols or special characters that represent other characters. You can use them with any command such as ls command or rm command to list or remove files.

There are three main wildcards in Linux:

  • An asterisk (*) – matches one or more occurrences of any character, including no character.
  • Question mark (?) – represents or matches a single occurrence of any character.
  • Bracketed characters ([ ]) – matches any occurrence of character enclosed in the square brackets. 

To Match Filenames Using Wildcards in Linux

 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*


This example shows another use of * to copy all filenames prefixed with users-0 and ending with one or more occurrences of any character.

$ mkdir -p users-info
$ ls users-0*
$ mv -v users-0* users-info/	# Option -v flag enables verbose output

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).

$ ls l?st.sh


The command below matches all files with names starting with l followed by any of the characters in the square bracket but ending with st.sh.

$ ls l[abdcio]st.sh 

To Combine Wildcards to Match Filenames in Linux


This command will match all filenames prefixed with any two characters followed by st but ending with one or more occurrence of any character.

$ ls
$ ls ??st*

This example matches filenames starting with any of these characters [clst] and ending with one or more occurrence of any character.

$ ls
$ ls [clst]*

In this examples, only filenames starting with any of these characters [clst] followed by one of these [io] and then any single character, followed by a t and lastly, one or more occurrence of any character will be listed.

$ ls
$ ls [clst][io]?t*

Here, filenames prefixed with one or more occurrence of any character, followed by the letters tar and ending with one or more occurrence of any character will be removed.

$ ls
$ rm *tar*
$ ls


To Match Characters Set in Linux


Now lets look at how to specify a set of characters. Consider the filenames below containing system users information.

$ ls
users-111.list  users-1AA.list  users-22A.list  users-2aB.txt   users-2ba.txt
users-111.txt   users-1AA.txt   users-22A.txt   users-2AB.txt   users-2bA.txt
users-11A.txt   users-1AB.list  users-2aA.txt   users-2ba.list
users-12A.txt   users-1AB.txt   users-2AB.list  users-2bA.list

To Negate a Set of Characters in Linux

You can as well negate a set of characters using the ! symbol. The following command lists all filenames starting with users-i, followed by a number, any valid file naming character apart from a number, then a lower or upper case letter and ends with one or more occurrences of any character.

$ ls users-[0-9][!0-9][a-zA-Z]*


Was this answer helpful? 0 Users Found This Useful (0 Votes)