You probably already use globbing characters without knowing
it. When you specify a file in Windows® or when you look for a
file, you use *
to match a random string. For example,
*.txt
matches all files with names ending with
.txt
. We also used it heavily in the last section. But
there is more to globbing than just *
.
When you type a command
like ls *.txt and press Enter,
the task of finding which files match the *.txt
pattern is not done by the ls command, but by the
shell
itself. This requires a little explanation about how
a command line is interpreted by the shell
. When you
type:
$ ls *.txt readme.txt recipes.txt
the command line is first split into words
(ls
and *.txt
in this example). When
the shell sees a *
in a word, it will interpret the
whole word as a globbing pattern and will replace it with the names of all
matching files. Therefore, the command, just before the shell executes it,
has become ls readme.txt recipe.txt, which gives the
expected result. Other characters make the shell react this way
too:
?
: matches one and only
one character, regardless of what that character is;
[...]
: matches any character found
in the brackets. Characters can be referred to either as a range of
characters (i.e. 1-9
) or discrete
values, or even both. Example:
[a-zBE5-7]
will match all characters between
a
and z
, a B
,
an E
, a 5
, a
6
or a 7
;
[!...]
: matches any
character not found in the brackets.
[!a-z]
, for example, will match any character which
is not a lowercase letter[5];
{c1,c2}
:
matches c1
or c2
, where
c1
and c2
are also globbing
patterns, which means you can write
{[0-9]*,[acr]}
for
example.
Here are some patterns and their meanings:
/etc/*conf
: all files
in the /etc
directory with names ending in
conf
. It can match
/etc/inetd.conf
,
/etc/conf.linuxconf
, and also
/etc/conf
if such a file exists.
Remember that *
can also match an empty
string.
image/{cars,space[0-9]}/*.jpg
:
all file names ending with .jpg
in directories
image/cars
, image/space0
,
(...), image/space9
, if those directories
exist.
/usr/share/doc/*/README
: all
files named README
in all of
/usr/share/doc
's immediate subdirectories. This
will make /usr/share/doc/mandrake/README
match,
for example, but not
/usr/share/doc/myprog/doc/README
.
*[!a-z]
: all files
with names which do not end with a lowercase
letter in the current directory.
[5] Beware! While this is true for most languages, this
may not be true for your own language setting
(locale
). This depends on the
collating order. On some language
configurations, [a-z]
will match a, A, b, B,
(...), z. And remember the fact that some languages
have accentuated characters too...