You are on page 1of 2

Wildcards

Use the "." for a single character match. If you want to get a list of all five-character English
dictionary words starting with "c" and ending in "h" (handy for solving crosswords):
cathy ~> grep '\<c...h\>' /usr/share/dict/words
catch
clash
cloth
coach
couch
cough
crash
crush

If you want to display lines containing the literal dot character, use the -F option to grep.

For matching multiple characters, use the asterisk. This example selects all words starting with "c"
and ending in "h" from the system's dictionary:
cathy ~> grep '\<c.*h\>' /usr/share/dict/words
caliph
cash
catch
cheesecloth
cheetah
--output omitted--

If you want to find the literal asterisk character in a file or output, use single quotes. Cathy in the
example below first tries finding the asterisk character in /etc/profile without using quotes,
which does not return any lines. Using quotes, output is generated:
cathy ~> grep * /etc/profile

cathy ~> grep '*' /etc/profile


for i in /etc/profile.d/*.sh ; do

Pattern matching using Bash features


Character ranges
Apart from grep and regular expressions, there's a good deal of pattern matching that you can do
directly in the shell, without having to use an external program.
As you already know, the asterisk (*) and the question mark (?) match any string or any single
character, respectively. Quote these special characters to match them literally:
cathy ~> touch "*"

cathy ~> ls "*"


*

But you can also use the square braces to match any enclosed character or range of characters, if
pairs of characters are separated by a hyphen. An example:
cathy ~> ls -ld [a-cx-z]*
drwxr-xr-x 2 cathy cathy 4096 Jul 20 2002 app-defaults/
drwxrwxr-x 4 cathy cathy 4096 May 25 2002 arabic/
drwxrwxr-x 2 cathy cathy 4096 Mar 4 18:30 bin/
drwxr-xr-x 7 cathy cathy 4096 Sep 2 2001 crossover/
drwxrwxr-x 3 cathy cathy 4096 Mar 22 2002 xml/

This lists all files in cathy's home directory, starting with "a", "b", "c", "x", "y" or "z".
If the first character within the braces is "!" or "^", any character not enclosed will be matched. To
match the dash ("-"), include it as the first or last character in the set. The sorting depends on the
current locale and of the value of the LC_COLLATE variable, if it is set. Mind that other locales
might interpret "[a-cx-z]" as "[aBbCcXxYyZz]" if sorting is done in dictionary order. If you want to
be sure to have the traditional interpretation of ranges, force this behavior by setting LC_COLLATE
or LC_ALL to "C".

You might also like