Linux – File Name Globbing with *, ?, [ ]

Linux – File Name Globbing with *, ?, [ ]

Sometimes you want to do something to a group of files, e.g., delete all of them, without having to perform the command on each file individually. For example, suppose we want to delete all of the .c files in a directory. A wildcard is a pattern which matches something else. Two commonly used *nix wildcards are * (called star) and ? (question mark).

  • Star(*) means 0 or more characters
  • Question Mark(?) means exactly one character
  • Brackets([]) represents a set of characters

Commands involving filenames specified with wildcards are expanded by the shell (this is called globbing after the name of a former program called glob which used to do this outside the shell).

The ‘*’

file*’ will match any filename which starts with the characters “file”, and then is followed by zero or more occurrences of any character.


Suppose Fred’s home directory contains the files,

  • file01.cpp
  • file02.cpp
  • file03.cpp
  • file1.cpp
  • file01.o
  • file02.o
  • file03.o
  • file1.o

To delete all of the .c files, type,

$ rm *.c

To delete file01.cpp and file01.o,

$ rm file01.*

The ‘?’

The ‘?’ represents exactly one character.


Consider again Fred’s home directory from the previous example.

Delete file01.o, file02.o and file03.o, but not file1.o,

$ rm file??.o

Delete file01.o, but not file01.cpp,

$ rm file01.?

The ‘[ ]’ Glob

A set of characters can be specified with brackets [ ]. ‘[ab]’ means the single character can be a OR b. Ranges can also be specified (ex: ‘[1-57-9]’ represents 1-5 OR 7-9).


Delete file02.cpp and file03.cpp from Fred’s directory,

$ rm file0[23].cpp

This will delete any files that start with f or F (remember linux is case sensitive),

$rm [fF]*

To delete all files which start with the string “file” followed by a single letter type,

$ rm file[a-zA-Z]

The a-z and A-Z in the last example means all the letters in the range lowercase a-z or uppercase A-Z.

There’s more to wildcard matching than this, but this is enough to get you started.

More Examples

Remove all files that are exactly 1 character,

$rm ?

Let’s say you have a directory named ‘9-15-2007-Backup-Really-Long-Name-blah…’ Rather than typing the whole name, you could just type a subset of the string and use it with the cd command(change directory),

$ cd 9-15-2007*

If you have multiple folders that start with 9-15-2007, your directory will be changed to the first one alphabetically.

You can use file name globbing on most commands that accept files as arguments.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s