Wildcards

Many Unix utility programs accept a list of filenames on the command line. For example

$ rm afile.txt bfile.txt cfile.txt

To facilitate producing such lists, the shell has a wildcard expansion feature. In particular the following characters are used:

*       Matches zero or more of any character in a name.
?       Matches exactly one character.
[...]   Matches exactly one character in the set.

For example, to remove everything in the current directory use

$ rm *

If you are used to Windows, you might be tempted to use rm *.* This, however, only removes files that contain a dot character in their name. Not all files will match that specification.

Be sure you realize that the '*' in the example above is interpreted by the shell. That is, the shell finds all matching files and replaces the '*' on the command line with a list of the names. The rm program does not realize that you used a wildcard.

Thus if you want to handle wildcards in your own programs, all you need to do is be sure your program can process a list of file names off the command line. The shell will take it from there.

Suppose you wanted to remove the files memo1, memo2, and memo3. You might use

$ rm memo?

The shell will produce a list of file names that start with memo and have one additional character at the end of their name. Thus the file memo_list would not be matched while memox would be matched.

You could also do

$ rm memo[123]

Here the shell will only match the names memo1, memo2, or memo3 (if they exist). The file memox would be spared.

Finally you could do

$ rm memo[1-3]

The '-' character inside the square brackets implies a range. This is easier than typing all the possibilities if the range is large. For example

$ rm doc[A-Z].rev.[0-9]

Normally you use directories to partition your files into managable groups. However, if you also use sensible naming conventions for your files (distinctive extensions or prefixes), you can refer to different file sets within one directory using wildcard characters. For example, suppose I gave all my memos a .mmo extension. Then I could extract all the memos from a directory and move them into a $HOME/memos directory with a command such as

$ mv *.mmo $HOME/memos

I don't need to worry about accidently moving some other type of file out of the working directory.