LiveFire Labs: Online UNIX Training with Hands-on Internet Lab

"Taking a LiveFire Labs' course is an excellent way to learn Linux/Unix. The lessons are well thought out, the material is explained thoroughly, and you get to perform exercises on a real Linux/Unix box. It was money well spent."

Ray S.
Pembrook Pines, Florida

LiveFire Labs' UNIX and Linux Operating System Fundamentals course was very enjoyable. Although I regularly used UNIX systems for 16 years, I haven't done so since 2000. This course was a great refresher. The exercises were fun and helped me gain a real feel for working with UNIX/Linux OS. Thanks very much!"

Ming Sabourin
Senior Technical Writer
Nuance Communications, Inc.
Montréal, Canada

Read more student testimonials...

Receive UNIX Tips, Tricks, and Shell Scripts by Email

Custom Search

LiveFire Labs' UNIX Tip, Trick, or Shell Script of the Week

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#*_}

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##*_}

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}
$ print ${PWD##*/}

A more common method for achieving this particular objective is to use the basename command:

$ print $(basename ${PWD})

Revew basename's man page ($ man basename) to learn more.
Read the NEXT article in this series - Pattern Matching - Substrings - Part II