 |
|
Oracle Shell Scripting
Oracle UNIX/Linux script tips
|
Wildcards and Pattern
Matching
Wildcards provide a way to be less specific
about what you’re looking for in UNIX and Linux. This can be very
helpful for acting on several similarly named files or directories
at once, but wildcards must be used judiciously! It would be very
easy to destroy or delete every file in a directory with a poorly
placed wildcard.
The most popular wildcard is the * (commonly
referred to as star.) When used in a command like the ls
below it will match any number of occurrences (including zero) of
any character. Let’s say you want to look at every file in a
directory with .txt in the name:
$ ls
log1.log log3.log sample.txt
log2.log output.txt test_script.sh
$ ls *.txt
output.txt sample.txt
We can see that by using the * wildcard we can
easily narrow down the files we will see without having to name them
specifically. Less common but still quite useful is the ?
wildcard. The ? wildcard will match zero or one occurrence of any
character.
$ ls
log?.log
log1.log log2.log log3.log
If you want to get even more specific and match
one occurrence of only specific characters you can specify the
characters to match within [] brackets.
$ ls
log[2345].log
log2.log log3.log
As we see in this example the specified
characters are evaluated individually so instead of matching the
string 2345 the shell checks for the occurrence of each
character individually and displays matching results. A range of
characters can also be specified within brackets to look for any
single character within that range. The following example will
match the same files found by the previous one:
$ ls
log[2-5].log
log2.log log3.log
Ranges of letters can also be specified but it’s
important to remember that they will be case sensitive. For example
the range [a-z] will match any lowercase character while the
range [A-Z] will match any uppercase.
Finally the caret (^) may be used within
brackets to match anything but the listed characters or range. In
this example we’ll match any character except 2 through 5:
$ ls
log[^2-5].log
log1.log
Wildcards can be combined in almost limitless
ways to match groups of files but again, be careful! You want to be
sure you’re getting the right files and directories, no more, no
less.