Grep and Regular Expressions!

What the $[+*.

Introduction

In the previous section we looked at a collection of filters that would manipulate data for us. In this section we will look at another filter which is quite powerful when combined with a concept called regular expressions or re's for short. Re's can be a little hard to get your head around at first so don't worry if this stuff is a little confusing. I find the best approach is to go over the material and experiment on the command line a little, then leave it for a day or 3, then come back and have another go. You will be surprised but it will start to make more sense the second time. Masterming re's just takes practice and time so don't give up.

So what are they?

Regular expressions are similar to the wildcards that we looked at in section 7. They allow us to create a pattern. They are a bit more powerful however. Re's are typically used to identify and manipulate specific pieces of data. eg. we may wish to identify every line which contains an email address or a url in a set of data.

Re's are used all over the place. We will be demonstrating them here with grep but many other programs use them (including sed and vi which you learned about in previous sections) and many programming languages make use of them too.

I'll give you an introduction to them here in this section but there is much more they can do. If you are interested then I highly recommend going through our regular expression tutorial which goes into more detail.

The characters used in regular expressions are the same as those used in wildcards. Their behaviour is slightly different however. A common mistake is to forget this and get their functions mixed up.

eGrep

egrep is a program which will search a given set of data and print every line which contains a given pattern. It is an extension of a program called grep. It's name is odd but based upon a command which did a similar function, in a text editor called ed. It has many command line options which modify it's behaviour so it's worth checking out it's man page. ie the -v option tells grep to instead print every line which does not match the pattern.

egrep [command line options] <pattern> [path]

In the examples below we will use a similar sample file as in the last section. It is included below as a reference.

  1. cat mysampledata.txt
  2. Fred apples 20
  3. Susy oranges 5
  4. Mark watermellons 12
  5. Robert pears 4
  6. Terry oranges 9
  7. Lisa peaches 7
  8. Susy oranges 12
  9. Mark grapes 39
  10. Anne mangoes 7
  11. Greg pineapples 3
  12. Oliver rockmellons 2
  13. Betty limes 14

Let's say we wished to identify every line which contained the string mellon

  1. egrep 'mellon' mysampledata.txt
  2. Mark watermellons 12
  3. Oliver rockmellons 2

The basic behaviour of egrep is that is will print the entire line for every line which contains a string of characters matching the given pattern. This is important to note, we are not searching for a word but a string of characters.

Also note that we included the pattern within quotes. This is not always required but it is safer to get in the habit of always using them. They are required if your pattern contains characters which have a special meaning on the command line.

Sometimes we want to know not only which lines matched but their line number as well.

  1. egrep -n 'mellon' mysampledata.txt
  2. 3:Mark watermellons 12
  3. 11:Oliver rockmellons 2

Or maybe we are not interested in seeing the matched lines but wish to know how many lines did match.

  1. egrep -c 'mellon' mysampledata.txt
  2. 2

Learning Regular Expressions

The best way to learn regular expressions is to give the examples a try yourself, then modify them slightly to test your understanding. It is common to make mistakes in your patterns while you are learning. When this happens typically every line will be matched or no lines will be matched or some obscure set. Don't worry if this happens you haven't done any damage and you can easily go back and have another go. Remember you may hit the up arrow on your keyboard to get at your recent commands and also modify them so you don't need to retype the whole command each time.

If you're not getting the output you would like then here are some basic strategies.

  • First off, check for typo's. If you're like me then you're prone to making them.
  • Re read the content here. Maybe what you thought a particular operator did was slightly different to what it actually does and re reading you will notice a point you may have missed the first time.
  • Break your pattern down into individual components and test each of these individually. This will help you to get a feel for which parts of the pattern is right and which parts you need to adjust.
  • Examine your output. Your current pattern may not have worked the way you want but we can still learn from it. Looking at what we actually did match and using it to help understand what actually did happen will help us to work out what we should try changing to get closer to what we actually want.

Debuggex is an on-line tool that allows you to experiment with regular expressions and allows you to visualise their behaviour. It can be a good way to better understand how they work.

Regular Expression Overview

I will outline the basic building blocks of re's below then follow on with a set of examples to demonstrate their usage.

  • . (dot) - a single character.
  • ? - the preceding character matches 0 or 1 times only.
  • * - the preceding character matches 0 or more times.
  • + - the preceding character matches 1 or more times.
  • {n} - the preceding character matches exactly n times.
  • {n,m} - the preceding character matches at least n times and not more than m times.
  • [agd] - the character is one of those included within the square brackets.
  • [^agd] - the character is not one of those included within the square brackets.
  • [c-f] - the dash within the square brackets operates as a range. In this case it means either the letters c, d, e or f.
  • () - allows us to group several characters to behave as one.
  • | (pipe symbol) - the logical OR operation.
  • ^ - matches the beginning of the line.
  • $ - matches the end of the line.

Some Examples

We'll start with something simple. Let's say we wish to identify any line with two or more vowels in a row. In the example below the multiplier {2,} applies to the preceding item which is the range.

  1. egrep '[aeiou]{2,}' mysampledata.txt
  2. Robert pears 4
  3. Lisa peaches 7
  4. Anne mangoes 7
  5. Greg pineapples 3

How about any line with a 2 on it which is not the end of the line. In this example the multiplier + applies to the . which is any character.

  1. egrep '2.+' mysampledata.txt
  2. Fred apples 20

The number 2 as the last character on the line.

  1. egrep '2$' mysampledata.txt
  2. Mark watermellons 12
  3. Susy oranges 12
  4. Oliver rockmellons 2

And now each line which contains either 'is' or 'go' or 'or'.

  1. egrep 'or|is|go' mysampledata.txt
  2. Susy oranges 5
  3. Terry oranges 9
  4. Lisa peaches 7
  5. Susy oranges 12
  6. Anne mangoes 7

Maybe we wish to see orders for everyone who's name begins with A - K.

  1. egrep '^[A-K]' mysampledata.txt
  2. Fred apples 20
  3. Anne mangoes 7
  4. Greg pineapples 3
  5. Betty limes 14

Summary

egrep
View lines of data which match a particular pattern.
Regular Expressions
A powerful way to identify particular pieces of information.

Activities

Let's identify some information.

  • First off, you may want to make a file with data similar to our sample file.
  • Now play with some of the examples we looked at above.
  • Have a look at the man page for egrep and try atleast 2 of the command line options for them.