Linux First Steps
computer software
Linux First Steps Linux First Steps
Linux First Steps   Home | Site Map | About Us | Products | Services | News | Contact Us | Links Linux First Steps
Linux First Steps Linux First Steps

Copyright © 2009

Linux® Bible


Using File-Matching Metacharacters
To save you some keystrokes and to be able to refer easily to a group of files, the bash shell lets you
use metacharacters. Anytime you need to refer to a file or directory, such as to list it, open it, or
remove it, you can use metacharacters to match the files you want. Here are some useful metachar-
acters for matching filenames:
*
-- Matches any number of characters.
?
-- Matches any one character.
[...]
-- Matches any one of the characters between the brackets, which can include a
dash-separated range of letters or numbers.
Try out some of these file-matching metacharacters by first going to an empty directory (such as
the
test
directory described in the previous section) and creating some empty files:
$ touch apple banana grape grapefruit watermelon
The
touch
command creates empty files. The next few commands show you how to use shell
metacharacters with the
ls
command to match filenames. Try the following commands to see if
you get the same responses:
$ ls a*
apple
$ ls g*
grape
grapefruit
$ ls g*t
grapefruit
$ ls *e*
apple grape grapefruit watermelon
$ ls *n*
banana watermelon
The first example matches any file that begins with an
a
(
apple
). The next example matches any
files that begin with
g
(
grape
,
grapefruit
). Next, files beginning with
g
and ending in
t
are
matched (
grapefruit
). Next, any file that contains an
e
in the name is matched (
apple
,
grape
,
grapefruit
,
watermelon
). Finally, any file that contains an
n
is matched (
banana
,
water-
melon
).
Here are a few examples of pattern matching with the question mark (
?
):
$ ls ????e
apple grape
$ ls g???e*
grape grapefruit
The first example matches any five-character file that ends in
e
(
apple
,
grape
). The second
matches any file that begins with
g
and has
e
as its fifth character (
grape
,
grapefruit
).
70
Linux First Steps
Part I