? | any single character, except a leading dot |
* | zero or more characters, except a leading dot |
[ ] | defines a class of characters ( - for range, ! to exclude) |
Examples:
[abc]?? | 3 character filename beginning with "a", "b", or "c". |
[1-9][A-Z] | 2 character filename starting with a number, and ending with an uppercase letter. |
[!A-Z]?? | 3 character filename that does not begin with an uppercase letter. |
*e[0-9]f | any file ending with "e", a single number, and "f". |
Note:this is similar to (but not the same as) pattern matching we saw
with grep.
Consider the following:
-rw-r--r--. 1 root
root 0 Jul 21 09:19 bap
-rw-r--r--. 1 root
root 0 Jul 21 09:19
bapper
-rw-r--r--. 1 root
root 0 Jul 21 09:20
bapperization
-rw-r--r--. 1 root
root 0 Jul 21 09:27
bill5
-rw-r--r--. 1 root
root 0 Jul 21 09:19 cap
-rw-r--r--. 1 root
root 0 Jul 21 09:26 cat
-rw-r--r--. 1 root
root 0 Jul 21 09:27 cat9
-rw-r--r--. 1 root
root 0 Jul 21 09:19 dap
-rw-r--r--. 1 root
root 0 Jul 21 09:26 dog
-rw-r--r--. 1 root
root 0 Jul 21 09:19 fap
-rw-r--r--. 1 root
root 0 Jul 21 09:27
jason7
-rw-r--r--. 1 root
root 0 Jul 21 09:28
leonard679
-rw-r--r--. 1 root
root 0 Jul 21 09:27
mouse
-rw-r--r--. 1 root
root 0 Jul 21 09:27
nathan3
ls -al [bc]a* will return
-rw-r--r--. 1 root root 0 Jul 21 09:19 bapWildcards in grep
. |
any single character |
* | match the preceding character zero or more times |
+ |
match the preceding character one or more times |
[ ] | defines a class of characters ( - for range, ^ to exclude) |
Anchors in grep
^ |
Match to the beginning of a line |
$ |
Match to the end of a line |
Examples:
[abc].. | 3 character filename beginning with "a", "b", or "c". |
[1-9][A-Z] | 2 character filename starting with a number, and ending with an uppercase letter. |
[^A-Z].. | 3 character filename that does not begin with an uppercase letter. |
>cat file
big
bad bug
bag
bigger
boogy
>grep b.g file
big
bad bug
bag
bigger
notice that boogy didn't match, since the "." matches exactly one
character.
The repetition meta-characters * and +
the expression consisting of a character followed by
a star matches any number (possibly zero) of repetitions of that
character. In particular, the expression ".*" matches any string, and
hence acts as a "wildcard". Note that ".*" can match NO characters, but ".+" must have at least one character.
Examples:
>cat file
big
bad bug
bag
bigger
boogy
Wildcards #1
>grep "b.*g" file
big
bad bug
bag
bigger
boogy
Wildcards #2
>grep "b.*g." file
bigger
boogy
Other examples:
grep "^[0-9]" testfile <---- `find all lines in file testfile that begin with a digit
grep "^[^0-9]" testfiel <----- find all lines in file testfile that begin with any character OTHER than a digit
grep "cat+" testfile <-----find all lines in file testfile that contain either cat catt cattt cattttt (etc.)