December
1, 2003 -
Pattern Matching - Substrings - Part I
|
|
The
Korn shell provides four pattern matching
(substring) operators. These
operators give you the ability to extract
a portion of a variable, or in other
words, discard the part you do not want.
First, we'll discuss the two operators
that remove characters from the beginning
(or left side) of the variable:
|
${variable#pattern}
- discards the smallest matching
pattern; returns the rest
${variable##pattern} - discards the
largest matching pattern; returns the
rest
|
|
In
the following example, since the pattern
(*_) matches the beginning of the variable
TEXT, the specified action will be
performed.
|
$ TEXT="livefire_labs_provides_online_unix_training_with_hands_on_lab_exercises"
$ print ${TEXT#*_}
labs_provides_online_unix_training_with_hands_on_lab_exercises
$
|
From the output
you can see that only "livefire_"
was dropped. This is because only one
pound sign (#) was used in the
statement. Using two pound signs will
delete the largest matching pattern from the
variable:
|
$ print ${TEXT##*_}
exercises
$
|
Even though
pattern matching has a wide variety of
applications, it is frequently used to parse
file or directory pathnames. This
example parses the full pathname of the
present working directory, leaving only the
name of the subdirectory the user is in:
|
$ print ${PWD}
/export/home/livefire
$ print ${PWD##*/}
livefire
$
|
A more common
method for achieving this particular
objective is to use the basename command:
|
$ print $(basename ${PWD})
livefire
$
|
Review
basename's man page ($ man basename) to
learn more.
Next week's tip
will use pattern matching to parse the end
of a variable.
|
|
|
|
|
|
|
Learn
more...
If you are new to the UNIX or Linux
operating system and would like to learn
more, you may want to consider
registering for LiveFire Labs' UNIX
and Linux Operating System Fundamentals
online training course.
If you already have a solid grasp of the
fundamentals but would like to learn more
about the Korn shell and basic and
advanced shell scripting, taking our Korn
Shell Scripting course will be
beneficial to you.
Our
innovative hands-on training model allows
you to learn
UNIX by completing hands-on
exercises on real servers in our Internet
Lab.
More
Tips...
· Popular
UNIX Tips from the Past
|
|