Читать книгу Linux Bible - Christopher Negus - Страница 126
Using file-matching metacharacters
ОглавлениеTo save you some keystrokes and enable you 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, open, or remove it, you can use metacharacters to match the files you want. Here are some useful metacharacters 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 hyphen-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 commands that follow show you how to use shell metacharacters with the ls
command to match filenames. Try the following commands to see whether 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 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 e
in the name is matched (apple
, grape
, grapefruit
, watermelon
). Finally, any file that contains n
is matched (banana
, watermelon
).
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
).
The following examples use braces to do pattern matching:
$ ls [abw]* apple banana watermelon $ ls [agw]*[ne] apple grape watermelon
In the first example, any file beginning with a
, b
, or w
is matched. In the second, any file that begins with a
, g
, or w
and also ends with either n
or e
is matched. You can also include ranges within brackets. For example:
$ ls [a-g]* apple banana grape grapefruit
Here, any filenames beginning with a letter from a
through g
are matched.