Search for basic patterns using grep

Bonnie Eisenman
InstructorBonnie Eisenman

Share this video with your friends

Send Tweet
Published 6 years ago
Updated 4 years ago

By using wildcards and glob patterns with the special characters . and *, you can create regular expressions that describe what kind of text you're looking for, instead of just plaintext strings.

[00:00] The first special character with grep regular expressions that we're going to look at today is the special character dot. I'm going to type grep dash dash color, and then, I'm going to look for h dot and We're just going to be looking at the readme right now.

[00:14] You can see with the color fog turned on what exactly this is matching. We're getting ht, ha, hi, and that's because dot matches exactly one character and it can be anything.

[00:25] Similarly, we can have a longer string, something a bit more practical, maybe http dot will return everything that matches https, but http will also work, because it's matching on that next colon character.

[00:38] Now, a dot will get interpreted as a special character. If you want to search for just a literal period, plain text, not use it as a wildcard, you're going to have to escape it. Let's say I wanted to look for dot-com, in the readme, I would type backslash and then dot-com. Now, you can see that this will match on dot-com just fine.

[00:57] The next character we're going to look at is the star or asterisk character. Some people call this glob. We're going to type grep dash dash color, and then two pound signs, a star, and we're going to look at readme.

[01:09] What this does is it says, OK, first, we're going to have one pound sign, and then the star applies to the previous character, and then, zero or more other pound signs. What we can see is that this pattern will match one pound sign. It can also match as many repeated as we want.

[01:27] This really becomes powerful in combination with the wildcard character. If I do grep dash dash color, and then let's say that I want parenthesis and then dot star, closing parenthesis, what this does is this search looks for an opening and closing parentheses, and then in the middle, any number of characters of any type.

[01:48] With markdown, we get basically all of these lengths, as well as any parent that will call comments or image files, as well. Using the combination dot star in your regular expressions when you're searching for things with grep, lets you define queries where you might not know or care about all of the characters in the query, but it lets you say what shape it should have, nevertheless.