Difference between revisions of "Tutorial9: Regular Expressions"
(→INVESTIGATION 1: SIMPLE & COMPLEX REGULAR EXPRESSIONS) |
(→INVESTIGATION 1: SIMPLE & COMPLEX REGULAR EXPRESSIONS) |
||
Line 139: | Line 139: | ||
# Let's issue a command to display strings that contain more than one occurrence of the letter x:<br><span style="color:blue;font-weight:bold;font-family:courier;">grep "xx*" textfile1.txt | more</span><br><br>Why did this work? because the pattern indicates one occurrence of the letter x, followed by zero or MORE occurrences of the letter x.<br><br>If you combine the complex regular expression symbols .* it will act like zero or more occurrence of any character (like * did in filename expansion).<br><br> | # Let's issue a command to display strings that contain more than one occurrence of the letter x:<br><span style="color:blue;font-weight:bold;font-family:courier;">grep "xx*" textfile1.txt | more</span><br><br>Why did this work? because the pattern indicates one occurrence of the letter x, followed by zero or MORE occurrences of the letter x.<br><br>If you combine the complex regular expression symbols .* it will act like zero or more occurrence of any character (like * did in filename expansion).<br><br> | ||
# Issue the following command to match strings begin and end with a number with nothing or anything inbetween:<br><span style="color:blue;font-weight:bold;font-family:courier;">grep "^[0-9].*[0-9]$" textfile1.txt | more</span><br><br>Using simultaneous anchors combined with the .* symbol(s) can help you to refine your search patterns of strings.<br><br> | # Issue the following command to match strings begin and end with a number with nothing or anything inbetween:<br><span style="color:blue;font-weight:bold;font-family:courier;">grep "^[0-9].*[0-9]$" textfile1.txt | more</span><br><br>Using simultaneous anchors combined with the .* symbol(s) can help you to refine your search patterns of strings.<br><br> | ||
− | # Issue the following linux pipeline command to display strings that begin with a capital letter, ends with a number, and contains a capital X somewhere inbetween:<br><span style="color:blue;font-weight:bold;font-family:courier;">grep "^[A-Z].*X.*[0-9]$" textfile1.txt | more</span><br><br>Let's look at another series of examples involving error-checking with numbers so only strings containing valid numbers are displayed.<br><br> | + | # Issue the following linux pipeline command to display strings that begin with a capital letter, ends with a number, and contains a capital X somewhere inbetween:<br><span style="color:blue;font-weight:bold;font-family:courier;">grep "^[A-Z].*X.*[0-9]$" textfile1.txt | more</span><br><br>Let's look at another series of examples involving '''error-checking''' with numbers so only strings containing valid numbers are displayed.<br><br> |
# First, issue the following linux command to download another data file called numbers.dat:<br><span style="color:blue;font-weight:bold;font-family:courier;">wget <nowiki>https://ict.senecacollege.ca/~murray.saul/uli101/numbers.dat</nowiki></span><br><br> | # First, issue the following linux command to download another data file called numbers.dat:<br><span style="color:blue;font-weight:bold;font-family:courier;">wget <nowiki>https://ict.senecacollege.ca/~murray.saul/uli101/numbers.dat</nowiki></span><br><br> | ||
# View the contents of the '''numbers.dat''' file using the '''more''' command and quickly view the contents of this file. You should notice valid and invalid numbers contained in this file. When finished, exit the more command.<br><br> | # View the contents of the '''numbers.dat''' file using the '''more''' command and quickly view the contents of this file. You should notice valid and invalid numbers contained in this file. When finished, exit the more command.<br><br> |
Revision as of 09:16, 6 July 2020
Contents
USING REGULAR EXPRESSIONS
Main Objectives of this Practice Tutorial
- Explain the purpose of Regular Expressions
- Understand the difference between Regular Expressions and Filename Expansion
- Understand the purpose of Literal (Simple) Regular Expressions
- Understand common symbols for Complex Regular Expressions and their purpose
- Understand command symbols for Extended Regular Expressions and their purpose
- Use various Linux commands that use regular expressions
Tutorial Reference Material
Course Notes |
Linux Command/Shortcut Reference |
YouTube Videos | ||
Course Notes:
|
Regular Expressions
|
Additional Linux Commands that Use Regular Expressions | Brauer Instructional Videos: |
KEY CONCEPTS
A regular expression … is a sequence of characters that define a search pattern.
Usually such patterns are used by string searching algorithms for "find" or "find and replace" operations on strings, or for input validation.
Reference: https://en.wikipedia.org/wiki/Regular_expression
Regular Expressions vs. Filename Expansion
Filename Expansion symbols are used to search, edit and manipulate text and are used with Linux file management commands such as ls, rm, mv, cp, cat, less and more. This can represent text contained in files or text as a result of issuing Linux commands using a pipeline.
A regular expression is a combination of two types of characters: literals and special characters.
In combination, these characters define a logical pattern. Strings of text can be compared to this pattern
to see if they fit the pattern defined by the expression.
Reference: https://www.whoishostingthis.com/resources/regex/
Literal (Simple) Regular Expressions
The simplest regular expression is a series of letters and numbers, possibly including white space (tabs or space characters), that have no special meaning. Such a regular expression consists of ``literals; that is, normal letters, which match only an identical letter in the data being searched.For example:
"This is a regular expression"
When an editor searches for a literal regular expression, it can only score a ``hit if it finds exactly that sequence of characters in the data it is searching.
Reference: http://osr507doc.xinuos.com/en/OSUserG/_Literal_chars_in_regexps.html
Complex Regular Expressions
The problem with using literals or simple regular expressions is that general patterns are matched.
For example, the pattern “the” would be matched for larger word containing that pattern like there, they, either, them, their, etc. Another problem is that you may want to search for pattern at a specific location within the string of text (like at the beginning or end).
There are other regular expression tools to provide more precise matches. These tools are complex and extended regular expressions.
Complex Regular Expressions use symbols to help match text for more precise or complex patterns. The most common complex regular expression symbols are displayed below:
- Anchors ^ , $
- Characters .
- Character Class [ ] , [^ ]
- Zero or More Occurrence *
Examples of how to use these complex regular expressions with the grep command are displayed below:
Extended Regular Expressions
Extended Regular Expressions consist of additional special characters the “extend” the capability of regular expressions.
Repetition {min,max} , ? , +
Allows for more precise repetitions. Using braces, you can specify the minimum and maximum number of repetitions.
Grouping ( )
Perhaps you want to search for repetition for a group of characters, a word, or a phase.
You can enclose them within brackets ( ) to specify a group.
or Condition |
Can be used with grouping to match a variety of character(s), words or phases. The | symbol is used to separate the variety of character(s).
Examples of how to use these complex regular expressions with the grep command are displayed below:
INVESTIGATION 1: SIMPLE & COMPLEX REGULAR EXPRESSIONS
In this section, you will learn how to use the grep command with simple and complex regular expressions to help search for patterns contained in text files.
Perform the Following Steps:
- Login your matrix account.
- Issue a command to confirm you are located in your home directory.
The wget command is used to download files from the Internet to your shell.
This will be useful to download text files that we will be using for this tutorial. - Issue the following linux command (copy and paste to save time):
wget https://ict.senecacollege.ca/~murray.saul/uli101/textfile1.txt - Issue the ls command to confirm that the text file was downloaded.
- View the contents of the textfile1.txt file using the more command and quickly view the contents of this file. When finished, exit the more command.
Although there are several Linux commands that use regular expressions, we will only be using the grep command for this section. - Issue the following linux pipeline command to match the pattern the within textfile1.txt:
grep "the" textfile1.txt | more - Now, issue the grep linux pipeline command with the -i option to ignore case sensitively:
grep -i "the" textfile1.txt | more
What do you notice is different with this pipeline command?
You will notice that the pattern "the" is matched including larger words that contain the pattern "the". You can use the -w option with the grep command in order to just match only words for a pattern. - Issue the following linux pipeline command:
grep -w -i "the" textfile1.txt | more
You should now see only strings of text that match the word "the".
Just matching literal or simple regular expressions can be useful, but are limited in what they can assist with pattern matching.
For Example, you may want to search for pattern at a specific location within the string of text (like at the beginning or end of the string).
There are other regular expression tools to provide more precise matches. These tools are complex and extended regular expressions. We will now look at complex regular expression symbols now, and we will discuss extended regular expressions'Italic text' in the next section of this tutorial. - Issue the following Linux pipeline command:
grep -w -i "^the" textfile1.txt | more
The ^ symbol is an anchor. In this case, it only matches the word "the" (both upper or lowercase) at the beginning of strings.
The $ symbol is used to anchor patterns at the end of strings. - Issue the following Linux pipeline command:
grep -w -i "the$" textfile1.txt | more
What do you notice? - Issue the following Linux pipeline command to anchor the work "the" simultaneously at the beginning and the end of the string:
grep -w -i "^the$" textfile1.txt | more
What do you notice?
Anchoring patterns at both the beginning and ending of strings can greatly assist for more complex search patterns.
We will now be demonstrating simultaneous anchoring with other complex regular expressions symbols. - Issue the following command to match strings that begin with 3 characters:
grep "^..." textfile1.txt | more
What do you notice? - Issue the following command to match strings that begin and end with 3 characters:
grep "^...$" textfile1.txt | more
What do you notice? - Issue the following command to match strings that begin with 3 digits:
grep "^[0-9][0-9][0-9]" textfile1.txt | more - Issue the following command to match strings that end with 3 uppercase letters:
grep "[A-Z][A-Z][A-Z]$" textfile1.txt | more - Issue the following command to match strings that consist of only 3 digits:
grep "^[0-9][0-9][0-9]$" textfile1.txt | more
The * complex regular expression symbol is often confused with filename expansion. In other words, it does NOT represent zero or more of any character, but zero or or occurrences of the character that comes before the * symbol. - To demonstration, issue the following command to display zero or more occurrences of the letter x:
grep "x*" textfile1.txt | more
You will most likely notice most lines of the file is displayed. - Let's issue a command to display strings that contain more than one occurrence of the letter x:
grep "xx*" textfile1.txt | more
Why did this work? because the pattern indicates one occurrence of the letter x, followed by zero or MORE occurrences of the letter x.
If you combine the complex regular expression symbols .* it will act like zero or more occurrence of any character (like * did in filename expansion). - Issue the following command to match strings begin and end with a number with nothing or anything inbetween:
grep "^[0-9].*[0-9]$" textfile1.txt | more
Using simultaneous anchors combined with the .* symbol(s) can help you to refine your search patterns of strings. - Issue the following linux pipeline command to display strings that begin with a capital letter, ends with a number, and contains a capital X somewhere inbetween:
grep "^[A-Z].*X.*[0-9]$" textfile1.txt | more
Let's look at another series of examples involving error-checking with numbers so only strings containing valid numbers are displayed. - First, issue the following linux command to download another data file called numbers.dat:
wget https://ict.senecacollege.ca/~murray.saul/uli101/numbers.dat - View the contents of the numbers.dat file using the more command and quickly view the contents of this file. You should notice valid and invalid numbers contained in this file. When finished, exit the more command.
- Issue the following linux command to display strings that begin with a capital letter, ends with a number, and contains a capital X somewhere inbetween:
grep "^[A-Z].*X.*[0-9]$" textfile1.txt | more
Let's look at another
INVESTIGATION 2: EXTENDED REGULAR EXPRESSIONS
In this section, you will learn how to ...
Perform the Following Steps:
- x
In the next investigation, you will ...
INVESTIGATION 3: OTHER COMMANDS THAT USE REGULAR EXPRESSIONS
In this section, you will learn how to ...
Perform the Following Steps:
- x
LINUX PRACTICE QUESTIONS
The purpose of this section is to obtain extra practice to help with quizzes, your midterm, and your final exam.
Here is a link to the MS Word Document of ALL of the questions displayed below but with extra room to answer on the document to simulate a quiz:
https://ict.senecacollege.ca/~murray.saul/uli101/uli101_command_practice_9a.docx
Your instructor may take-up these questions during class. It is up to the student to attend classes in order to obtain the answers to the following questions. Your instructor will NOT provide these answers in any other form (eg. e-mail, etc).
Review Questions:
Part A: Display Results from Linux Commands using Regular Expressions
Note the contents from the following tab-delimited file called ~murray.saul/uli101/cars:
Plym fury 77 73 2500 chevy nova 79 60 3000 ford mustang 65 45 10003 volvo gl 78 102 9850 ford ltd 83 15 10507 chevy nova 80 50 3503 fiat 600 65 115 450 honda accord 81 30 6000 ford thundbd 84 10 17000 toyota tercel 82 180 755 chevy impala 65 85 1553 ford bronco 83 25 9505
Write the results of each of the following Linux commands using regular expressions for the above-mentioned file.
1. grep plym ~murray.saul/uli101/cars
2. grep -i fury ~murray.saul/uli101/cars
3. grep “^[m-z]” ~murray.saul/uli101/cars
4. grep -i “^[m-z]” ~murray.saul/uli101/cars
5. grep “3$” ~murray.saul/uli101/cars
6. grep -i “c.*5$” ~murray.saul/uli101/cars
Part B: Writing Linux Commands Using Regular Expressions
7. Write a Linux command to display all lines in the file called ~/text.txt that contains the pattern:
the
8. Write a Linux command to display all lines in the file called ~/text.txt that contains the word: the
9. Write a Linux command to display all lines in the file called ~/text.txt that begin with a number.
10. Write a Linux command to display all lines in the file called ~/text.txt that end with a letter
(either upper or lowercase).
11. Write a Linux command to display all lines in the file called ~/text.txt that begin and end with a number.
12. Write a Linux command to display all lines in the file called ~/text.txt that contains exactly 3 characters that can be anything.
13. Write a Linux command to display all lines in the file called ~/text.txt that contains exactly 3 numbers.
14. Write a Linux command to display all lines in the file called ~/text.txt that contains 1 or more “C” characters.
If you wish additional practice using extended regular expressions, here is a link to another MS Word document:
https://ict.senecacollege.ca/~murray.saul/uli101/uli101_command_practice_9b.docx