[MUSIC PLAYING]
Today we'll talk about anchoring with regex.
So 'egrep' is a Linux command that finds a given
regular expression in the lines of a file.
For example, "egrep 'regex' file".
And we'll also be using a word list that's in Linux called
'/usr/share/dict/words' that has about 10,000 words.
So we can use this with 'egrep', for example,
to find a word that starts with 'ant'.
And now you might see how we found
a lot of words that don't start with 'ant',
but actually contain 'ant'.
And while this might be useful sometimes,
it might not be what we're meaning to do.
So if we wanted to do what we're meaning to do,
we'll actually have to use the special caret symbol, which
is a regex symbol that specifies that we
want to anchor our word to the beginning of a line.
So now when we run this command, we'll
see we get all the words that begin with 'ant', which is great.
But what if we wanted to do the opposite:
what if we wanted to find all words that end with 'ant'?
So what we can do then is we can use a special dollar sign
symbol, which is an anchor to the end of a word.
And so we'll put this here.
And now we said, "OK, egrep, find all words that end with 'ant'".
And now we've got this.
This is great.
But we could also use both.
And if we use both, we can then find
all the words that begin with 'ant' and end with 'ant'.
And as a consequence, we just find the single word, 'ant',
which is great.
But what if we want to find the words that begin with 'ant'
or another word like 'age'.
Then we can use 'egrep' again.
And we can specify the pipe symbol,
so 'ant' or 'age', which would basically say,
"I want to look for the word 'ant' or 'age'."
And we're also putting the caret.
But now you might see that we've just broken something.
Doesn't work how it was supposed to work.
So this is because we forgot to put in--
We forget to put it in our single quotes.
And our single quotes are important,
because they specify to the shell,
"don't use these as normal shell characters".
So now that we've done that, you can
see that we've gotten all words that end with 'age'.
And further up, we'll have words that start with 'ant'.
However, this again is not what we want to do.
If we want to fix this, we'll need
to specify either to group 'ant' and 'age' together.
So we can use the grouping operator for that.
And now we've got words that start with 'ant'
or 'age' further up.
Or what we can also do is we can specify
the anchor to the beginning of both of the words.
And now that will say, finding words that begin with 'ant'
or begin with 'age'.
And we'll get the same output.
So I hope you have found this video useful
and it has helped you in understanding
the importance of anchors in searching through strings.
Thank you.
[MUSIC PLAYING]